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();
        }
Beispiel #2
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());
            }
        }
Beispiel #3
0
 /// <summary>
 /// Instantiate a map layer.
 /// </summary>
 /// <param name="width">Width of the layer measured in tiles</param>
 /// <param name="height">Height of the layer measured in tiles</param>
 public MapLayer(int width, int height)
 {
     map = new Tile[height, width];
     for (int y = 0; y < height; y++)
         for (int x = 0; x < width; x++)
             map[y, x] = null;//new Tile(0, 0);
 }
 public Map(string path)
 {
     tiles = new int[25, 19];
     tilelist = new Tile[25, 19];
     load("map_1.txt");
     keyboard = new KeyboardState();
 }
 public Map(string path)
 {
     tiles = new int[25, 19];
     tilelist = new Tile[25, 19];
     init();
     keyboard = new KeyboardState();
 }
Beispiel #6
0
	void GenerateTiles ()
	{
		width_tiles = tile_terrain_grid [0].Length;
		height_tiles = tile_terrain_grid.Length;
//        float width_unity = (float)width_tiles * tile_width;
//        float height_unity = (float)height_tiles * tile_height;

		tile_grid = new Tile[width_tiles, height_tiles];

		for (int y = 0; y < height_tiles; ++y) {
			for (int x = 0; x < width_tiles; ++x) {
				float y_unity = ((float)y + 0.5f) * tile_height;
				float x_unity = ((float)x + 0.5f) * tile_width;

				Tile tile = tile_root.InstantiateChild<Tile> (tile_prefab);
				tile.x = x;
				tile.y = y;
				tile.transform.localPosition = new Vector3 (x_unity, y_unity);
				tile.terrain = parseTerrain (tile_terrain_grid [y] [x]);
				tile.road_direction = parseRoadDirection (tile_road_grid [y] [x]);
				setSprite (tile, tile.terrain);
				tile.transform.localScale = getScaleToFillTile (tile.sprite);
				tile.gameObject.SetActive (true);

				tile_grid [x, y] = tile;
			}
		}
	}
Beispiel #7
0
        public Tilemap(int w, int h, Tilemap ft)
        {
            cmap = new CityMap(w, h);
            map = new Tile[w, h];
            fog = new Fog(w, h);
            name = ft.name;

            startpos = new Point(ft.startpos.X, ft.startpos.Y);

            for (int i = 0; i < w; i++)
                for (int e = 0; e < h; e++)
                {
                    if (i < ft.NumX && e < ft.NumY)
                    {
                        map[i, e] = ft.get(i, e);
                        fog.set(i, e, ft.Fog.get(i, e));
                        cmap.set(i, e, ft.CityMap.get(i, e));
                    }
                    else if (i < w && e < h)
                    {
                        map[i, e] = new Tile();
                        fog.set(i, e, false);
                    }
                }
        }
    private float Width; //width (X) of map

    #endregion Fields

    #region Methods

    //Builds all the fluff
    public void BuildFluff(Tile [,] gd, float scale)
    {
        //Prep variables
        Fluff = new GameObject();
        Fluff.name = "Fluff";
        Fluff.transform.position = new Vector3(0f, 0f, 0f);
        Grid = gd;
        Scale = scale;
        Width = gd.GetLength(0);
        Height = gd.GetLength(1);

        //Loop through the grid, adding fluff spots as appropriate
        for (int i = 1; i < Width - 1; i++)
        {
            for (int j = 1; j < Height - 1; j++)
            {
                //Check walls
                if (Grid[i, j].getType() == "Rock")
                {
                    AddWallLight(i, j);
                }

                //Check floors
                if (Grid[i, j].getType() == "Floor")
                {
                    //AddCornerLight(i, j); not fully functional yet
                    AddParticles(i, j);
                }
            }
        }
    }
Beispiel #9
0
        public TiledMap(GraphicsDevice graphicsDevice)
        {
            map = new Tile[mapWidth, mapHeight];
            tiles = new Dictionary<string, Tile>();
            /* Creating the tiles */
            tiles.Add("mur", new Tile(graphicsDevice, "mur", "mur"));
            tiles.Add("sol", new Tile(graphicsDevice, "sol", "sol"));
            tiles.Add("sortie", new Tile(graphicsDevice, "sortie", "sortie"));
            tiles.Add("trou", new Tile(graphicsDevice, "trou", "trou"));

            /* Surrounding walls */
            for (int x = 0; x < MapWidth; x++)
            {
                map[x, 0] = tiles["mur"];
                map[x, MapHeight - 1] = tiles["mur"];
            }
            for (int y = 0; y < MapHeight; y++)
            {
                map[0, y] = tiles["mur"];
                map[MapWidth - 1, y] = tiles["mur"];
            }

            /* Floor */
            for (int x = 1; x < MapWidth - 1; x++)
            {
                for (int y = 1; y < MapHeight - 1; y++)
                {
                    map[x, y] = tiles["sol"];
                }
            }
        }
Beispiel #10
0
        public Grid(World world) {
            using (StreamReader sr = new StreamReader("testmap.txt")) {
                List<string> lines = new List<string>();
                while (!sr.EndOfStream) {
                    lines.Add(sr.ReadLine());
                }
                xDimension = lines[0].Length;
                yDimension = lines.Count;
                tiles = new Tile[xDimension, yDimension];
                for (int i = 0; i < xDimension; i++)
                {
                    for (int j = 0; j < yDimension; j++)
                    {
                        tiles[i, j] = new Tile(i, j, new Rectangle((int)(i*TileSize),(int)(j*TileSize),(int)TileSize,(int)TileSize));
                        if (lines[j][i] == '#')
                        {
                            tiles[i, j].passable = false;
                            Body body = BodyFactory.CreateRectangle(world, ConvertUnits.ToSimUnits(TileSize), ConvertUnits.ToSimUnits(TileSize), 10, ConvertUnits.ToSimUnits(GetWindowCenterPos(tiles[i, j])));
                            body.BodyType = BodyType.Static;
                            body.CollidesWith = Category.All;
                            body.CollisionCategories = Category.All;
                            tileBodies.Add(body);
                        }
                            
                    }
                }

            }

            AssignNeighbours();

            pathfinder = new Pathfinder(this);

        }
Beispiel #11
0
        /// <summary>
        ///  Create a TileSet of X and Y Tiles
        /// </summary>
        /// <param name="_TileXCount">Tile Set * of X Tiles</param>
        /// <param name="_TileYCount">Tile Set * of Y Tiles</param>
        public TileSet(int _TileXCount, int _TileYCount)
        {
            this.TileXCount = _TileXCount;
            this.TileYCount = _TileYCount;

            this.Tiles = NewTileSet();
        }
Beispiel #12
0
    static void Main(string[] args) {
        string[] inputs;
        inputs = Console.ReadLine().Split(' ');
        int W = int.Parse(inputs[0]);
        int H = int.Parse(inputs[1]);
        Tiles = new Tile[W, H];
        inputs = Console.ReadLine().Split(' ');
        int X = int.Parse(inputs[0]);
        int Y = int.Parse(inputs[1]);
        for (int y = 0; y < H; y++) {
            string R = Console.ReadLine();
            for (int x = 0; x < R.Length; x++) {
                Tiles[x, y] = new Tile(x, y, R[x] == '#');
                Tiles[x, y].BuildLinks(W, H);
                if ((x == 0 || y == 0 || x == W - 1 || y == H - 1) && !Tiles[x, y].IsWall) {
                    OuterTiles.Add(Tiles[x, y]);
                }
            }
        }

        Tile start = Tiles[X, Y];
        foreach (Tile t in OuterTiles) {
            if (DistanceBetween(start, t) != -1) {
                EntryPoints.Add(t);
            }
        }

        EntryPoints = EntryPoints.OrderBy(e => e.X).ThenBy(e => e.Y).ToList();
        Console.WriteLine(EntryPoints.Count);
        foreach (Tile t in EntryPoints) {
            Console.WriteLine("{0} {1}", t.X, t.Y);
        }
    }
Beispiel #13
0
 public BattleMap(Game game, int x, int y)
 {
     height = x;
     width = y;
     map = new Tile[x,y];
     random = new RandomNumberGenerator();
 }
Beispiel #14
0
 public Layer(Map map)
 {
     Map = map;
     Rows = map.Rows;
     Cols = map.Cols;
     Tiles = new Tile[Rows, Cols];
 }
Beispiel #15
0
 public TileLayer(int width, int height, string name, Tile[,] data)
 {
     _width = width;
     _height = height;
     _name = name;
     _data = data;
 }
Beispiel #16
0
        public Area(int w, int h)
        {
            width = w;
            height = h;
            map = new Tile[width, height];

            int x = 0;
            int y = 0;
            Random rand = new Random();

            for (w = 0; w < width; w++)
            {
                for (h = 0; h < height; h++)
                {
                    bool walkable;

                    if (rand.Next(10) < 9)
                        walkable = true;
                    else
                        walkable = false;

                    if(walkable)
                        map[w, h] = new Tile(new Vector2(x * 32, y * 32), "grass", walkable);
                    else
                        map[w, h] = new Tile(new Vector2(x * 32, y * 32), "water", walkable);

                    y++;
                }

                x++;
                y = 0;
            }
        }
Beispiel #17
0
        public TileMap(int width, int height, Texture texture)
        {
            Width = width;
            Height = height;

            var lastTile = texture == null ? ushort.MaxValue : (ushort)((texture.Size.X / GameOptions.TileSize) * (texture.Size.Y / GameOptions.TileSize) - 1);

            tiles = new Tile[width, height];

            for (var y = 0; y < height; y++)
            {
                for (var x = 0; x < width; x++)
                {
                    tiles[x, y].Index = lastTile;
                    tiles[x, y].Solid = false;
                }
            }

            var chunkWidth = (width / GameOptions.TileChunkSize) + 1;
            var chunkHeight = (height / GameOptions.TileChunkSize) + 1;

            chunks = new Chunk[chunkWidth, chunkHeight];

            for (var y = 0; y < chunkHeight; y++)
            {
                for (var x = 0; x < chunkWidth; x++)
                {
                    chunks[x, y] = new Chunk(x, y, tiles, texture);
                }
            }
        }
Beispiel #18
0
        //Battle Tile Array uses 32x32 px tiles.  Also includes tileSpriteLookup metadata object
        private void loadBattleTileArray(GameObject tileMapGameObject)
        {

            string strTileArray = "";

            Bounds mapBounds = tileMapGameObject.GetComponentInChildren<Renderer>().bounds;

            int tileWidth = (int)Math.Ceiling(mapBounds.size.x );
            int tileHeight = (int)Math.Ceiling(mapBounds.size.y );

            battleTileArray = new Tile[tileWidth, tileHeight];
            for (int y = 0; y < tileHeight; y++)
            {
                for (int x = 0; x < tileWidth; x++)
                {
                 
                    Vector3 center = new Vector3(x + Tile.TILE_SIZE, -y + Tile.TILE_SIZE,0);
                    Vector3 size = new Vector3(Tile.TILE_SIZE, Tile.TILE_SIZE);
                    Bounds tileBounds = new Bounds(center, size);
                    bool empty = !checkCollision(tileBounds);

                    battleTileArray[x, y] = new Tile(x, y, empty);

                    //Extra metadata on tile
                    battleTileArray[x, y].tileSpriteLookup = getTileSpriteLookup(tileBounds, x, y, empty);

                    strTileArray += empty ? "." : "#";
                }
                strTileArray += System.Environment.NewLine;
            }
            int i = 1;
        }
        public GameState(int width, int height, 
		                  int turntime, int loadtime, 
		                  int viewradius2, int attackradius2, int spawnradius2)
        {
            Width = width;
            Height = height;

            LoadTime = loadtime;
            TurnTime = turntime;

            ViewRadius2 = viewradius2;
            AttackRadius2 = attackradius2;
            SpawnRadius2 = spawnradius2;

            MyAnts = new List<Ant>();
            MyHills = new List<AntHill>();
            EnemyAnts = new List<Ant>();
            EnemyHills = new List<AntHill>();
            DeadTiles = new List<Location>();
            FoodTiles = new List<Location>();

            map = new Tile[height, width];
            for (int row = 0; row < height; row++) {
                for (int col = 0; col < width; col++) {
                    map[row, col] = Tile.Land;
                }
            }
        }
Beispiel #20
0
    public Map(int w, int h)
    {
        width = w;
        height = h;

        tiles = new Tile[height, width];
    }
Beispiel #21
0
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            #region
            tiles = new Tile[4, 4];
            tiles[0, 0] = b00;
            tiles[0, 1] = b01;
            tiles[0, 2] = b02;
            tiles[0, 3] = b03;

            tiles[1, 0] = b10;
            tiles[1, 1] = b11;
            tiles[1, 2] = b12;
            tiles[1, 3] = b13;

            tiles[2, 0] = b20;
            tiles[2, 1] = b21;
            tiles[2, 2] = b22;
            tiles[2, 3] = b23;

            tiles[3, 0] = b30;
            tiles[3, 1] = b31;
            tiles[3, 2] = b32;
            tiles[3, 3] = b33;
            #endregion
            btn.Focus(FocusState.Programmatic);
            NewGame(times++);
        }
Beispiel #22
0
 public Game(int width, int height, int mines)
 {
     this.height = height;
     this.width = width;
     this.mines = mines;
     tiles = new Tile[width, height];
     for (int i = 0; i < this.width; i++)
         for (int j = 0; j < this.height; j++)
             tiles[i, j] = new Tile();
     Random rand = new Random();
     for (int i = 0; i < mines; )
     {
         int r1 = rand.Next(width);
         int r2 = rand.Next(height);
         if (tiles[r1, r2].status == Tile.TileStatus.CLEAN)
         {
             tiles[r1, r2].status = Tile.TileStatus.MINED;
             i++;
         }
     }
     timer = new System.Timers.Timer();
     timer.Interval = 1000;
     timer.Elapsed += new System.Timers.ElapsedEventHandler(onTick);
     timer.Start();
 }
        public override void Generate()
        {
            tileMapObject = new GameObject(GraphName);
            tileMapObject.transform.parent = GraphContainer;
            tileMapObject.transform.position = GraphPosition;
            tileMapObject.tag = GraphTag;

            tileMap = tileMapObject.AddComponent<TileMap>();
            tiles = new Tile[GraphWidth, GraphHeight];

            for (int y = 0; y < GraphHeight; y++)
            {
                for (int x = 0; x < GraphWidth; x++)
                {
                    tilePrefab = GetTilePrefab();
                    tileObject = GameObject.Instantiate(tilePrefab) as GameObject;
                    tile = tileObject.GetComponent<Tile>();

                    tileObject.name = "(" + x + ", " + y + ") " + tilePrefab.name;
                    tileObject.transform.parent = tileMapObject.transform;
                    tileObject.transform.position = new Vector3(x, y, 0);

                    tiles[x, y] = tile;
                }
            }

            tileMap.SetNodes(tiles);

            if (OnGenerationComplete != null)
                OnGenerationComplete(GraphWidth, GraphHeight);
        }
    /*private enum Resources : int
    {
        Stone,
        Timber,
        Ore,
        Coal,
        Tool,
        Weapon,
        Cart,
        Empty
    }*/
    public TileScript(int x, int y)
    {
        mapSizeX_ = x;
        mapSizeY_ = y;

        tiles_ = new Tile[mapSizeX_, mapSizeY_];
    }
        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();
        }
Beispiel #26
0
	public PrototypeBoard(int dimension, TileFactory tileFactory) {
		_dimensionOfBoard = dimension;
		_tileFactory = tileFactory;
		_tileArray = new Tile[dimension, dimension];

		BuildBoard (dimension);
	} 
Beispiel #27
0
 public Maze(Game game, int size)
     : base(game)
 {
     graphicsDevice = game.GraphicsDevice;
     this.size = size;
     tiles = new Tile[size, size];
 }
Beispiel #28
0
        public void CreateTiles(Stream fileStream)
        {
            int width;
            List<string> lines = new List<string>();
            using (StreamReader reader = new StreamReader(fileStream))
            {
                string line = reader.ReadLine();
                width = line.Length;
                while (line != null)
                {
                    lines.Add(line);
                    if (line.Length != width)
                        throw new Exception(String.Format("The length of line {0} is different from all preceeding lines.", lines.Count));
                    line = reader.ReadLine();
                }
            }

            // Allocate the tile grid.
            tiles = new Tile[width, lines.Count];
            height = lines.Count;
            this.width = width;

            for (int y = 0; y < lines.Count; ++y)
            {
                for (int x = 0; x < width; ++x)
                {
                    // to load each tile.
                    int tempType = (int)Char.GetNumericValue(lines[y][x]);

                    int tileType = (tempType == -1) ? (int)lines[y][x]: tempType ;
                    tiles[x, y] = LoadTile(tileType, x, y);
                }
            }
        }
Beispiel #29
0
 public Terrain(int mSizeX, int mSizeY)
 {
     _sizeX = mSizeX;
     _sizeY = mSizeY;
     _tiles = new Tile[_sizeX,_sizeY];
     Rooms = new List<Room> ();
 }
Beispiel #30
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++;
                            }
                        }
                    }
                }
            }
        }
        public static void GenerateTileMaps(
            IList <Bitmap> bitmaps
            , byte paletteBankIndexOffset
            , out Color[] masterPalette
            , out Tile[] masterTileSet
            , out TileMap[] tileMaps
            , bool skipSort = false
            )
        {
            List <ProcessedPaletteContainer> bitmapPalettes = new List <ProcessedPaletteContainer>();

            // Validate bitmaps and collect palettes
            for (int bitmapIndex = 0; bitmapIndex < bitmaps.Count; ++bitmapIndex)
            {
                Bitmap bitmap = bitmaps[bitmapIndex];

                Size size = bitmap.Size;

                if (size.Width % TileConfig.TileWidth != 0 || size.Height % TileConfig.TileHeight != 0)
                {
                    throw new Exception("Size not compatible with GBA tiles. Width and height of pixels must be multiples of 8.");
                }

                int     xStart = 0;
                int     yStart = 0;
                int     width  = bitmap.Width;
                int     height = bitmap.Height;
                Color[] preProcessedPalette = PaletteHelper.GeneratePaletteFromImage(bitmap, xStart, yStart, width, height);

                // Validate pallet length
                {
                    if (preProcessedPalette.Length > PaletteHelper.MAX_PALETTE_LENGTH)
                    {
                        throw new Exception(string.Format("Palette length ({0}) out of range for the GBA ({1})", preProcessedPalette.Length, PaletteHelper.MAX_PALETTE_LENGTH));
                    }
                }

                ProcessedPaletteContainer palContainer = new ProcessedPaletteContainer();
                palContainer.bitmapIndex = bitmapIndex;
                palContainer.palette     = preProcessedPalette;

                bitmapPalettes.Add(palContainer);
            }

            if (!skipSort)
            {
                // Sort bitmap palette. Anything more than 16 colours should be grouped next to each other. Less than 16 should always be a full 16.
                bitmapPalettes.Sort(new ProcessedPaletteComparer());
            }

            // Get palettes of each image, merge into a master palette
            List <Color> masterPaletteList = new List <Color>();
            List <ProcessedBitmapContainer> processedBitmapList = new List <ProcessedBitmapContainer>();

            {
                Color transparencyColour = Color.FromArgb(0);

                for (int i = 0; i < bitmapPalettes.Count; ++i)
                {
                    var bp = bitmapPalettes[i];

                    Debug.Assert(bp.palette[0] == transparencyColour);

                    bool pal4bbp      = bp.palette.Length <= PaletteHelper.PALETTE_LENGTH_4BBP;
                    int  paletteIndex = pal4bbp ? Find4bbpPaletteIndex(masterPaletteList, bp.palette) : -1;

                    if (pal4bbp && paletteIndex < 0)    // Add the new palette in
                    {
                        // Make sure our 4bbp palette is aligned properly, every set of 16 colour palettes starts with pure transparency
                        while (masterPaletteList.Count % PaletteHelper.PALETTE_LENGTH_4BBP != 0)
                        {
                            masterPaletteList.Add(transparencyColour);
                        }

                        // TODO
                        // If 2 bitmap palettes can fit in the same GBA palette, merge them into one.
                        paletteIndex = Get4bbpPaletteIndexForSize(masterPaletteList);

                        masterPaletteList.AddRange(bp.palette);
                    }

                    if (!pal4bbp)
                    {
                        // Only add colour into the master palette if it's not already in there.
                        foreach (Color col in bp.palette)
                        {
                            if (!masterPaletteList.Contains(col))
                            {
                                masterPaletteList.Add(col);
                            }
                        }
                    }

                    if ((paletteIndex + paletteBankIndexOffset) >= PaletteHelper.MAX_PALETTE_INDEX)
                    {
                        throw new Exception(string.Format("Palette index {0} with palette bank offset {1} is not valid for map data", paletteIndex, paletteBankIndexOffset));
                    }

                    ProcessedBitmapContainer pbc = new ProcessedBitmapContainer();
                    pbc.bitmapIndex  = bp.bitmapIndex;
                    pbc.paletteIndex = paletteIndex;
                    pbc.bitmap       = bitmaps[bp.bitmapIndex];

                    processedBitmapList.Add(pbc);
                }
            }

            masterPalette = masterPaletteList.ToArray();

            Console.WriteLine("Total colours found = " + masterPalette.Length);

            if (masterPalette.Length >= PaletteHelper.MAX_PALETTE_LENGTH)
            {
                throw new Exception(string.Format("Master palette has too many colours ({0}/{1})", masterPalette.Length, PaletteHelper.MAX_PALETTE_LENGTH));
            }

            Console.WriteLine("Processing master tileset");

            // Get all unique tiles sorted via palette indicies. Need to check if local palette was greater than 16 or not
            List <Tile> uniqueTileSetList = new List <Tile>();

            foreach (ProcessedBitmapContainer pbc in processedBitmapList)
            {
                Tile[,] rawTileMap = BitmapToTileArray(pbc.bitmap, masterPalette, pbc.paletteIndex);
                pbc.rawTileMap     = rawTileMap;

                FillUniqueTileset(rawTileMap, uniqueTileSetList);
            }

            masterTileSet = uniqueTileSetList.ToArray();

            // Generate tilemaps from master list. Remember palette index, but we should be able to forget about it. We can overlap tiles that are the same but different colours.
            List <TileMap> tileMapList = new List <TileMap>();

            foreach (ProcessedBitmapContainer pbc in processedBitmapList)
            {
                TileMap tilemap = new TileMap(pbc.rawTileMap, masterTileSet, pbc.paletteIndex);
                tileMapList.Add(tilemap);
            }

            tileMaps = tileMapList.ToArray();
        }
Beispiel #32
0
    void MoveToLeft(Tile[,] a)
    {
        int TurnLimit = 0;
        int n         = 2;

        while (n != 0)
        {
            for (int i = 0; i < 4; i++)
            {
                for (int j = 3; j > 0; j--)
                {
                    //swap
                    if (a[i, j].Appear != 0 && a[i, j - 1].Appear == 0)
                    {
                        a[i, j - 1].Appear = a[i, j].Appear;
                        a[i, j].Appear     = 0;
                    }

                    //merge and score
                    if (a[i, j].Appear == a[i, j - 1].Appear && a[i, j - 1].Appear != 0 && a[i, j].Appear != 0)
                    {
                        a[i, j - 1].Appear = a[i, j - 1].Appear + 1;
                        a[i, j].Appear     = 0;
                        ScorePoint         = (int)Math.Pow(2, a[i, j - 1].Appear);
                        ScoreForLevelUp.Instance.ScoreUpdate += ScorePoint;
                    }
                    if (a[i, j].Appear != a[i, j - 1].Appear && a[i, j].Appear != 0 && a[i, j - 1].Appear != 0)
                    {
                        TurnLimit += 1;
                    }
                }
            }
            n--;
        }
        ScoreForLevelUp.Instance.TurnUpdate -= 1;
        if (TurnLimit == 24)//Can/t move there
        {
            ScoreForLevelUp.Instance.TurnUpdate -= 1;
        }

        n = 2;
        int GOCount = 0;

        while (n != 0)
        {
            for (int i = 0; i < 3; i++)
            {
                for (int j = 3; j > 0; j--)
                {
                    if (a[i, j].Appear != 0)
                    {
                        if (a[i, j].Appear != a[i + 1, j].Appear && a[i, j].Appear != a[i, j - 1].Appear &&
                            a[i, j].Appear != 0 && a[i + 1, j].Appear != 0 && a[i, j - 1].Appear != 0
                            )
                        {
                            GOCount += 1;
                        }
                    }
                }
            }
            n--;
        }



        if (ScoreForLevelUp.Instance.TurnUpdate == 90)
        {
            GameOver();
        }
        else if (GOCount == (18))
        {
            for (int k = 0; k < 6; k++)
            {
                if (a[0, 0].Appear != a[1, 0].Appear && a[1, 0].Appear != a[2, 0].Appear && a[2, 0].Appear != a[3, 0].Appear &&
                    a[3, 3].Appear != a[3, 2].Appear && a[3, 2].Appear != a[3, 1].Appear && a[3, 1].Appear != a[3, 0].Appear
                    )
                {
                    GameOver();
                    break;
                }
            }
        }
    }
Beispiel #33
0
 public Map()
 {
     Tiles          = new TileType[(int)MapSize.X, (int)MapSize.Y];
     ProbabilityMap = new int[(int)MapSize.X, (int)MapSize.Y];
     DrawTiles      = new Tile[(int)MapSize.X, (int)MapSize.Y];
 }
Beispiel #34
0
        static void Main(string[] args)
        {
            Console.WriteLine("Difficulty: 'easy' 'normal' 'hard' 'harder'");
            Console.Write("Rows: ");
            rows = int.Parse(Console.ReadLine());
            Console.Write("Cols: ");
            cols = int.Parse(Console.ReadLine());
            Console.Write("Mines/Difficulty: ");
            MineNumb(ref mines);

            Random random = new Random();

            field = new Tile[rows, cols];

            for (int i = 0; i < rows; i++)
            { // mezők létrehozása
                for (int j = 0; j < cols; j++)
                {
                    field[i, j] = new Tile();
                    Tile.NotMines++; // mezők száma, később kivonva a bombák számával
                }
            }

            for (int i = 0; i < mines; i++)
            { // bombák "lerakása"
                int newRow = random.Next(field.GetLength(0));
                int newCol = random.Next(field.GetLength(1));

                if (field[newRow, newCol].Mines != -1)
                {                    // megnézi, hogy azon a random helyen a táblán már van-e bomba
                    field[newRow, newCol].Mines = -1;
                    Tile.NotMines--; // kivonja azt a mennyiséget, ahány bomba van
                }
                else
                {
                    i--;
                }
            }

            for (int i = 0; i < field.GetLength(0); i++)
            { // megadja azon mezők értékét, amik nem bombák (a körzetében lévő bombaszám)
                for (int j = 0; j < field.GetLength(1); j++)
                {
                    if (field[i, j].Mines != -1)
                    {
                        for (int k = -1; k <= 1; k++)
                        {
                            for (int l = -1; l <= 1; l++)
                            {
                                if (i + k != -1 && i + k != field.GetLength(0) &&
                                    j + l != -1 && j + l != field.GetLength(1))
                                {
                                    if (field[i + k, j + l].Mines == -1)
                                    {
                                        field[i, j].Mines++;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            DrawField();

            Console.CursorSize = 100; // kurzor előkészítése, a mezőn való mozgásra #graphics
            Console.CursorLeft = 0;
            Console.CursorTop  = 0;   // ez és az ez előtti teendők, mind a mező előkészítése

            Input();
        }
Beispiel #35
0
    public static float CalculateConnectedness(object _map)
    {
        Tile[,] map = (Tile[, ])_map;

        int totalOpenTiles = 0;

        bool[,] marked = new bool[map.GetLength(0), map.GetLength(1)];
        List <int[]> nbs = new List <int[]>();

        nbs.Add(new int[] { -1, 0 });
        nbs.Add(new int[] { 1, 0 });
        nbs.Add(new int[] { 0, -1 });
        nbs.Add(new int[] { 0, 1 });

        float largestOpenArea = 0;

        for (int i = 0; i < map.GetLength(0); i++)
        {
            for (int j = 0; j < map.GetLength(1); j++)
            {
                if (!map[i, j].BLOCKS_MOVEMENT)
                {
                    if (!marked[i, j])
                    {
                        float        thisAreaSize = 0;
                        List <int[]> open         = new List <int[]>();
                        List <int[]> visited      = new List <int[]>();
                        open.Add(new int[] { i, j });
                        int count = 0;

                        while (open.Count > 0)
                        {
                            thisAreaSize++;
                            totalOpenTiles++;
                            int[] p = open[0];
                            marked[p[0], p[1]] = true;

                            visited.Add(p);
                            open.Remove(open[0]);

                            foreach (int[] nb in nbs)
                            {
                                int dx = p[0] + nb[0];
                                int dy = p[1] + nb[1];
                                if (dx >= 0 && dy >= 0 && dx < map.GetLength(0) && dy < map.GetLength(1))
                                {
                                    bool seen = false;

                                    foreach (int[] v in open)
                                    {
                                        if (v[0] == dx && v[1] == dy)
                                        {
                                            seen = true;
                                            break;
                                        }
                                    }
                                    if (!seen && !marked[dx, dy] && !map[dx, dy].BLOCKS_MOVEMENT)
                                    {
                                        open.Add(new int[] { dx, dy });
                                    }
                                }
                            }
                        }
                        if (thisAreaSize > largestOpenArea)
                        {
                            largestOpenArea = thisAreaSize;
                        }
                    }
                }
            }
        }

        return(((float)largestOpenArea) / ((float)totalOpenTiles));
    }
Beispiel #36
0
    // Initialize empty grid.
    private void InitGrid(int width, int height)
    {
        SpriteRenderer spriteRenderer = tilePrefab.GetComponent <SpriteRenderer>();
        float          gridW          = spriteRenderer.bounds.size.x; // Get size of sprite.
        float          gridH          = spriteRenderer.bounds.size.y;
        Vector3        tilePos        = new Vector3(transform.position.x,
                                                    transform.position.y + (gridH * (height - 1)), // Tile at y position 0 should be at the top of the screen.
                                                    transform.position.z);

        // Destroy old grid.
        if (tileGrid != null)
        {
            for (int x = 0; x < sizeX; x++)
            {
                for (int y = 0; y < sizeY; y++)
                {
                    Destroy(tileGrid[x, y].gameObject);
                }
            }
        }

        sizeX = width;
        sizeY = height;

        // Create new grid.
        tileGrid = new Tile[sizeX, sizeY];

        for (int x = 0; x < sizeX; x++)
        {
            for (int y = 0; y < sizeY; y++)
            {
                Tile newTile = Instantiate(tilePrefab, tilePos, Quaternion.identity);

                newTile.transform.parent = transform;
                newTile.Pos     = new Vector2Int(x, y);
                newTile.TileMap = this;
                tileGrid[x, y]  = newTile;

                tilePos.y -= gridH;
            }

            tilePos.x += gridW;
            tilePos.y  = transform.position.y + (gridH * (sizeY - 1));
        }


        // Fit grid to screen.
        // https://pressstart.vip/tutorials/2018/06/6/37/understanding-orthographic-size.html
        Vector3 boardSize   = new Vector3(gridW * sizeX, gridH * (sizeY + 1), 0.0f);
        float   screenRatio = (float)Screen.width / (float)Screen.height;
        float   targetRatio = boardSize.x / boardSize.y;

        if (screenRatio >= targetRatio)
        {
            Camera.main.orthographicSize = boardSize.y / 2;
        }
        else
        {
            float differenceInSize = targetRatio / screenRatio;
            Camera.main.orthographicSize = boardSize.y / 2 * differenceInSize;
        }

        // Center grid inside camera view.
        Camera.main.transform.position = new Vector3((boardSize.x * 0.5f) - (gridW / 2.0f), (boardSize.y / 2.0f) - (gridH / 2.0f), Camera.main.transform.position.z);
    }
Beispiel #37
0
        public void Update2()
        {
            Player player = Main.LocalPlayer;

            if (selected && (EyeDropperActive || StampToolActive))
            {
                //			player.mouseInterface = true;
                //			player.showItemIcon = true;
                if (EyeDropperActive)
                {
                    //		Main.LocalPlayer.showItemIconText = "Click to select pallete";
                    player.showItemIcon2 = ItemID.EmptyDropper;
                    if (leftMouseDown)
                    {
                        Point point = (Main.MouseWorld).ToTileCoordinates();
                        //Point point = (Main.MouseWorld + (brushSize % 2 == 0 ? Vector2.One * 8 : Vector2.Zero)).ToTileCoordinates();
                        //point.X -= brushSize / 2;
                        //point.Y -= brushSize / 2;
                        if (startTileX == -1)
                        {
                            startTileX     = point.X;
                            startTileY     = point.Y;
                            lastMouseTileX = -1;
                            lastMouseTileY = -1;
                        }

                        //if (lastMouseTileX != point.X && lastMouseTileY != point.Y)
                        {
                            //for (int x = 0; x < brushSize; x++)
                            //{
                            //	for (int y = 0; y < brushSize; y++)
                            //	{
                            //		if (WorldGen.InWorld(x + point.X, y + point.Y))
                            //		{
                            //			Tile target = Framing.GetTileSafely(x + point.X, y + point.Y);
                            //			BrushTiles[x, y].CopyFrom(target);
                            //			//	Main.NewText("{x}, {y}");
                            //		}
                            //	}
                            //}
                            lastMouseTileX = point.X;
                            lastMouseTileY = point.Y;
                        }
                    }
                    if (justLeftMouseDown)
                    {
                        if (startTileX != -1 && startTileY != -1 && lastMouseTileX != -1 && lastMouseTileY != -1)
                        {
                            Vector2 upperLeft  = new Vector2(Math.Min(startTileX, lastMouseTileX), Math.Min(startTileY, lastMouseTileY));
                            Vector2 lowerRight = new Vector2(Math.Max(startTileX, lastMouseTileX), Math.Max(startTileY, lastMouseTileY));

                            int minX = (int)upperLeft.X;
                            int maxX = (int)lowerRight.X + 1;
                            int minY = (int)upperLeft.Y;
                            int maxY = (int)lowerRight.Y + 1;

                            //ErrorLogger.Log(string.Format("JustDown2 {0} {1} {2} {3}", minX, minY, maxX, maxY));

                            StampTiles = new Tile[maxX - minX, maxY - minY];

                            for (int i = 0; i < maxX - minX; i++)
                            {
                                for (int j = 0; j < maxY - minY; j++)
                                {
                                    StampTiles[i, j] = new Tile();
                                }
                            }

                            for (int x = minX; x < maxX; x++)
                            {
                                for (int y = minY; y < maxY; y++)
                                {
                                    if (WorldGen.InWorld(x, y))
                                    //if (WorldGen.InWorld(x + point.X, y + point.Y))
                                    {
                                        Tile target = Framing.GetTileSafely(x, y);
                                        StampTiles[x - minX, y - minY].CopyFrom(target);
                                        //	Main.NewText("{x}, {y}");
                                    }
                                }
                            }
                            //Main.NewText("EyeDropper: width height" + (maxX - minX) + " " + (maxY - minY));
                            CheatSheet.instance.paintToolsUI.AddSlot(PaintToolsEx.GetStampInfo(StampTiles));
                        }
                        //Main.NewText("EyeDropper: x,y,min max " + minX + " " + maxX + " " + minY + " " + maxY);

                        startTileX        = -1;
                        startTileY        = -1;
                        lastMouseTileX    = -1;
                        lastMouseTileY    = -1;
                        justLeftMouseDown = false;
                    }
                }
                if (StampToolActive)
                {
                    player.showItemIcon2 = ItemID.Paintbrush;
                    //		Main.LocalPlayer.showItemIconText = "Click to paint";
                    if (leftMouseDown && stampInfo != null)
                    {
                        int width  = StampTiles.GetLength(0);
                        int height = StampTiles.GetLength(1);
                        //Vector2 brushsize = new Vector2(width, height);
                        //Vector2 evenOffset = Vector2.Zero;
                        //if (width % 2 == 0)
                        //{
                        //	evenOffset.X = 1;
                        //}
                        //if (height % 2 == 0)
                        //{
                        //	evenOffset.Y = 1;
                        //}
                        //Point point = (Main.MouseWorld + evenOffset * 8).ToTileCoordinates();
                        ////Point point = (Main.MouseWorld + (brushSize % 2 == 0 ? Vector2.One * 8 : Vector2.Zero)).ToTileCoordinates();
                        //point.X -= width / 2;
                        //point.Y -= height / 2;
                        ////Vector2 vector = new Vector2(point.X, point.Y) * 16f;
                        ////vector -= Main.screenPosition;
                        ////if (Main.LocalPlayer.gravDir == -1f)
                        ////{
                        ////	vector.Y = (float)Main.screenHeight - vector.Y - 16f;
                        ////}

                        Point point = Snap.GetSnapPosition(CheatSheet.instance.paintToolsUI.SnapType, width, height, constrainToAxis, constrainedX, constrainedY, true).ToPoint();

                        if (startTileX == -1)
                        {
                            startTileX     = point.X;
                            startTileY     = point.Y;
                            lastMouseTileX = -1;
                            lastMouseTileY = -1;
                        }

                        if (Main.keyState.IsKeyDown(Keys.LeftShift))
                        {
                            constrainToAxis = true;
                            if (constrainedStartX == -1 && constrainedStartY == -1)
                            {
                                constrainedStartX = point.X;
                                constrainedStartY = point.Y;
                            }

                            if (constrainedX == -1 && constrainedY == -1)
                            {
                                if (constrainedStartX != point.X)
                                {
                                    constrainedY = point.Y;
                                }
                                else if (constrainedStartY != point.Y)
                                {
                                    constrainedX = point.X;
                                }
                            }
                            if (constrainedX != -1)
                            {
                                point.X = constrainedX;
                            }
                            if (constrainedY != -1)
                            {
                                point.Y = constrainedY;
                            }
                        }
                        else
                        {
                            constrainToAxis   = false;
                            constrainedX      = -1;
                            constrainedY      = -1;
                            constrainedStartX = -1;
                            constrainedStartY = -1;
                        }

                        if (lastMouseTileX != point.X || lastMouseTileY != point.Y)
                        {
                            lastMouseTileX = point.X;
                            lastMouseTileY = point.Y;
                            //Main.NewText("StartTileX " + startTileX);
                            UndoHistory.Push(Tuple.Create(point, new Tile[width, height]));
                            UpdateUndoTooltip();
                            for (int x = 0; x < width; x++)
                            {
                                for (int y = 0; y < height; y++)
                                {
                                    if (WorldGen.InWorld(x + point.X, y + point.Y) && StampTiles[x, y] != null)
                                    {
                                        Tile target = Framing.GetTileSafely(x + point.X, y + point.Y);
                                        UndoHistory.Peek().Item2[x, y] = new Tile(target);
                                        int cycledX = ((x + point.X - startTileX) % width + width) % width;
                                        int cycledY = ((y + point.Y - startTileY) % height + height) % height;
                                        if (TransparentSelectionEnabled)                                         // What about just walls?
                                        {
                                            if (StampTiles[cycledX, cycledY].active())
                                            {
                                                target.CopyFrom(StampTiles[cycledX, cycledY]);
                                            }
                                        }
                                        else
                                        {
                                            target.CopyFrom(StampTiles[cycledX, cycledY]);
                                        }
                                    }
                                }
                            }
                            if (Main.netMode == 1)
                            {
                                NetMessage.SendTileSquare(-1, point.X + width / 2, point.Y + height / 2, Math.Max(width, height));
                            }
                        }
                    }
                    else
                    {
                        startTileX        = -1;
                        startTileY        = -1;
                        constrainToAxis   = false;
                        constrainedX      = -1;
                        constrainedY      = -1;
                        constrainedStartX = -1;
                        constrainedStartY = -1;
                    }
                }
                Main.LocalPlayer.showItemIcon = true;
            }
        }
    //Build a room from an XML <room> entry
    public void BuildRoom(PT_XMLHashtable room)
    {
        //Destroy any old tiles
        foreach (Transform t in tileAnchor)
        {
            Destroy(t.gameObject);
        }

        //Move the mage out of the way
        Mage.S.pos = Vector3.left * 1000;
        Mage.S.ClearInput();

        string rNumStr = room.att("num");

        //Get the texture names for the floors and walls from <room> attribute
        string floorTexStr = room.att("floor");
        string wallTexStr  = room.att("wall");

        //Split the room into rows of tiles based on line breaks in Rooms.xml
        string[] roomRows = room.text.Split('\n');

        //Trim tabs from the beginnings of lines. However, we're leaving spaces and underscores to allow for non-rectangular rooms.
        for (int i = 0; i < roomRows.Length; i++)
        {
            roomRows[i] = roomRows[i].Trim('\t');
        }

        //Clear the tiles array
        tiles = new Tile[100, 100]; //Arbitrary max room size is 100X100

        //Declare a number of local fields that we'll use later
        Tile          ti;
        string        type, rawType, tileTexStr;
        GameObject    go;
        int           height;
        float         maxY    = roomRows.Length - 1;
        List <Portal> portals = new List <Portal>();

        //These loops scan through each tile of each row of the room
        for (int y = 0; y < roomRows.Length; y++)
        {
            for (int x = 0; x < roomRows[y].Length; x++)
            {
                //Set defaults
                height     = 0;
                tileTexStr = floorTexStr;

                //Get the character representing the tile
                type = rawType = roomRows[y][x].ToString();
                switch (rawType)
                {
                case " ":
                case "_":
                    //skip over empty space
                    continue;

                case ".":     // default floor
                    //Keep type "."
                    break;

                case "|":     //default wall
                    height = 1;
                    break;

                default:
                    //Anything else will be interpreted as floor
                    break;
                }

                //Set the texture for floor or wall based on <room> attributes
                if (type == ".")
                {
                    tileTexStr = floorTexStr;
                }
                else if (type == "|")
                {
                    tileTexStr = wallTexStr;
                }

                //Instantiate a new TilePrefab
                go = Instantiate(tilePrefab) as GameObject;
                ti = go.GetComponent <Tile>();

                //Set the parent Transform to tileAnchor
                ti.transform.parent = tileAnchor;

                //set the position of the tile
                ti.pos      = new Vector3(x, maxY - y, 0);
                tiles[x, y] = ti; // Add ti to the tiles 2D array

                //Set the type, height and texture of the Tile
                ti.type   = type;
                ti.height = height;
                ti.tex    = tileTexStr;

                //if the type is still rawType, continue to the next iteration
                ////**********//if (rawType == type)
                //**************    continue;

                //Check for specific entities in the room
                switch (rawType)
                {
                case "X":     // Starting position for the Mage
                    //Mage.S.pos = ti.pos;
                    if (firstRoom)
                    {
                        Mage.S.pos = ti.pos;
                        roomNumber = rNumStr;
                        firstRoom  = false;
                    }
                    break;

                case "0":
                case "1":
                case "2":
                case "3":
                case "4":
                case "5":
                case "6":
                case "7":
                case "8":
                case "9":
                case "A":
                case "B":
                case "C":
                case "D":
                case "E":
                case "F":
                    //instantiate a portal
                    GameObject pGO = Instantiate(portalPrefab) as GameObject;
                    Portal     p   = pGO.GetComponent <Portal>();
                    p.pos = ti.pos;
                    p.transform.parent = tileAnchor;     // attaching this to the tileAnchor means that the Portal will be destroyed when a new room is built
                    p.toRoom           = rawType;
                    portals.Add(p);
                    break;

                default:
                    //Try to see if theres an enemy for that letter
                    IEnemy en = EnemyFactory(rawType);
                    if (en == null)
                    {
                        break;
                    }
                    en.pos = ti.pos;
                    //Make en a child of tileAnchor so it's deleted when the next room is loaded
                    en.transform.parent = tileAnchor;
                    en.typeString       = rawType;
                    break;
                }
            }
        }
        //Position the Mage
        foreach (Portal p in portals)
        {
            //if p.toRoom is the same as the room number the Mage just exited
            //then the Mage should enter this room through this Portal
            //Alternatively, if firstRoom == true and there was no X in the
            //room (as a default Mage starting point), move the mage to this
            //Portal as a backup (if you start from a room different from 0
            if (p.toRoom == roomNumber || firstRoom)
            {
                //if there's an X in the Room, firstRoom will be set to false
                Mage.S.StopWalking();
                Mage.S.pos = p.pos; //move mage to this portal location

                //Mage maintains facing from the previous room, so there
                //is no need to rotate to enter this room to face the right direction
                p.justArrived = true;
                firstRoom     = false; // stops the mage to move to second portal
            }
        }
        roomNumber = rNumStr;
    }
Beispiel #39
0
        //Generate the level specified by levelNumber
        public static void GenerateLevel(int levelNumber)
        {
            //Clear data
            DeletePreviousArray();
            //Get new level data
            LevelContainerClass.levelInfo levelInfo = LevelContainerClass.extractLevelInfo(levelNumber);
            //Load Help Window
            levelInfoWindow = new LevelInfoWindow();

            //Get level rankings
            gold   = levelInfo.gold;
            silver = levelInfo.silver;
            bronze = levelInfo.bronze;
            //Update help window
            levelInfoWindow.lblMedalsList.Text = "Gold: " + gold.ToString() + "\nSilver: " + silver.ToString() + "\nBronze: " + bronze.ToString();
            //Reset the medal status icon
            if (Program.formRef != null)
            {
                Program.formRef.naPicMedalIcon.Image = global::TileGamePrototype.Properties.Resources.GoldMedal;
            }


            //Get list of objectives
            objectives = levelInfo.objectives;
            //Get list of items to collect
            itemsToCollect = levelInfo.itemsToCollect;
            //Check level robustness
            if (objectives.Contains(ObjectiveTypes.CollectItem) && itemsToCollect == null)
            {
                Console.WriteLine("Invalid Objectives Provided");
                return;
            }

            //Set variable used when checking if the player has to return to the village
            if (objectives.Contains(ObjectiveTypes.ReturnHome))
            {
                returnHome = true;
            }

            //////Update the help window with objective requirements
            string objectivesList = "";

            //Loop every objective. Not most efficient but convinient for getting the total count of any given objective. Enums are short so low cost
            foreach (ObjectiveTypes objective in Enum.GetValues(typeof(ObjectiveTypes)))
            {
                //Calculates the number of times that objective appears
                int count = ObjectiveOperators.getObjectiveOccurances(objectives, objective);
                //Check it is required
                if (count > 0)
                {
                    //List items that you need to find
                    if (objective == ObjectiveTypes.CollectItem)
                    {
                        objectivesList += "Collect Items: (" + ObjectiveOperators.getItemsToCollectString() + "), ";
                    }
                    //Ignore count for returning home
                    else if (objective == ObjectiveTypes.ReturnHome)
                    {
                        objectivesList += objective.ToString() + ", ";
                    }
                    //Else list how many times that objective is required
                    else
                    {
                        objectivesList += objective.ToString() + " x" + count.ToString() + ", ";
                    }
                }
            }
            objectivesList = objectivesList.Remove(objectivesList.Length - 2); // remove the last comma
            //Update help window
            levelInfoWindow.lblObjeciveList.Text     = objectivesList;
            levelInfoWindow.lblobjRemainingList.Text = objectivesList;

            //Get Relic for current level
            relic = levelInfo.relic;

            //Update help window
            if (objectives.Contains(ObjectiveTypes.ObtainRelic))
            {
                //Check level robustness
                if (relic == null)
                {
                    return;
                }
                //Show the relic info box in the help window
                levelInfoWindow.lblRelicInfoList.Text = relic.info;
                levelInfoWindow.lblRelicInfoList.Show();
                levelInfoWindow.lblRelicInfoTitle.Show();
            }


            //////Generate level using level builder
            currentLevelSurfaceArray = levelBuilder.buildLevelSurface(levelInfo);

            //Caves were going to be added, code accomadating their addition exists but will rarely be used (such as Zones etc.). Not worth removing at present.

            /*if (levelInfo.containsCave)
             * {
             *  currentLevelCaveArray = levelBuilder.buildLevelCave(levelInfo);
             * }*/

            //Give animals paths for moving. This is buggy and does not support multiple animals moving and they can walk on water :-P
            if (levelInfo.paths != null)
            {
                //Loops through every path provided
                foreach (KeyValuePair <System.Drawing.Point, int[]> entry in levelInfo.paths)
                {
                    System.Drawing.Point location = entry.Key;
                    int[] path = entry.Value;
                    Tile  tile = currentLevelSurfaceArray[location.X, location.Y];
                    //Checks if it is an animal and sets up its paths
                    if (tile.isLiving && !tile.isPlayer)
                    {
                        tile.setupPath(path);
                    }
                }
            }

            //Adds every animal to event
            foreach (Tile tile in currentLevelSurfaceArray)
            {
                if (tile.isLiving && !tile.isPlayer)
                {
                    player.playerMove += new Action(tile.playerAction);
                }
            }

            /*foreach (Tile tile in currentLevelCaveArray)
             * {
             *  if (tile.isLiving && !tile.isPlayer)
             *  {
             *      player.playerMove += new Action(tile.playerAction);
             *  }
             * }*/

            //Adds animal movement handler to the move event
            player.playerMove += new Action(AnimalMovementHandler.handleAllRequests);
            //Add move counter to move event
            player.playerMove += new Action(moveCounter);
            //Add objective checking function to move event
            player.playerMove += new Action(checkLevelComplete);
            //Add check for if the player is recently deceased to move event
            player.playerMove += new Action(checkPlayerStatus);
            //Add restart level to death event
            player.playerDeath += new Action(restartLevel);
        }
Beispiel #40
0
    void GenerateTileMap()
    {
        tileMap = new Tile[width, height];
        List <Tile> doorTiles = new List <Tile>();

        if (map != null)
        {
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    tileMap[x, y].positionX = x;
                    tileMap[x, y].positionY = y;

                    if (map[x, y] == 0)
                    {
                        tileMap[x, y].type = FLOOR;
                    }

                    if (map[x, y] == 1)
                    {
                        if ((x > 0 && map[x - 1, y] == 0) || (x < width - 1 && map[x + 1, y] == 0) || (y > 0 && map[x, y - 1] == 0) || (y < height - 1 && map[x, y + 1] == 0) || (x > 0 && y > 0 && map[x - 1, y - 1] == 0) || (x > 0 && y < height - 1 && map[x - 1, y + 1] == 0) || (x < width - 1 && y > 0 && map[x + 1, y - 1] == 0) || (x < width - 1 && y < height - 1 && map[x + 1, y + 1] == 0))
                        {
                            tileMap[x, y].type = OUTERWALL;
                        }
                        else
                        {
                            tileMap[x, y].type = OUTEROUTERWALL;
                        }
                    }
                }
            }

            //决定出入口
            if (GameObject.Find("GameManager(Clone)").GetComponent <GameManager>().level > 3)
            {
                tileMap[11, 0].type = ENTER;
                enterPositon        = new Vector3(11f, 0.0f, 0f);

                tileMap[11, 12].type = EXIT;
                exitPositon          = new Vector3(11f, 0.0f, 12f);
            }
            else
            {
                for (int x = 0; x < width; x++)
                {
                    for (int y = 0; y < height; y++)
                    {
                        if (x > 1 && x < width - 2 && tileMap[x + 1, y].type == OUTERWALL && tileMap[x - 1, y].type == OUTERWALL && tileMap[x + 2, y].type == OUTERWALL && tileMap[x - 2, y].type == OUTERWALL && ((y < height - 1 && tileMap[x, y + 1].type == FLOOR) || (y > 0 && tileMap[x, y - 1].type == FLOOR)))
                        {
                            doorTiles.Add(tileMap[x, y]);
                        }
                    }
                }

                int index = Random.Range(0, doorTiles.Count);

                tileMap[doorTiles[index].positionX, doorTiles[index].positionY].type = ENTER;
                enterPositon = new Vector3(doorTiles[index].positionX, 0.0f, doorTiles[index].positionY);
                Vector2 enterV = new Vector2(doorTiles[index].positionX, doorTiles[index].positionY);
                doorTiles.RemoveAt(index);

                index = Random.Range(0, doorTiles.Count);

                int   flag = 0;
                float max  = 0;
                for (int i = 0; i < doorTiles.Count; i++)
                {
                    Vector2 exitV = new Vector2(doorTiles[i].positionX, doorTiles[i].positionY);
                    if ((enterV - exitV).magnitude > max)
                    {
                        max  = (enterV - exitV).magnitude;
                        flag = i;
                    }
                }

                tileMap[doorTiles[flag].positionX, doorTiles[flag].positionY].type = EXIT;
                exitPositon = new Vector3(doorTiles[flag].positionX, 0.0f, doorTiles[flag].positionY);
            }
        }
    }
Beispiel #41
0
        private Pipe[,] createGrid(Pipe[,] pipeGrid, Tile[,] pathGrid, int width, int length)
        {
            int         x    = 0;
            int         y    = 0;
            int         x_   = 0;
            int         y_   = 0;
            int         _col = 0;
            int         _row = 0;
            Random      r    = new Random();
            int         rNum;
            SoundEffect _sound;

            for (x = 0; x < width; x++)
            {
                for (y = 0; y < length; y++)
                {
                    rNum = r.Next(0, 3);
                    if (rNum == 0 || rNum == 2)
                    {
                        _sound = soundLibrary[0];
                    }
                    else
                    {
                        _sound = soundLibrary[1];
                    }
                    x_ = 400 - (30 * width);
                    y_ = 300 - (30 * length);
                    Thread.Sleep(20);
                    if (pathGrid[x, y].tileType == 3)
                    {
                        rNum = r.Next(0, 3);
                        if (rNum == 0)
                        {
                            pathGrid[x, y].tileType = 0;
                        }
                        else if (rNum == 1)
                        {
                            pathGrid[x, y].tileType = 1;
                        }
                        else
                        {
                            pathGrid[x, y].tileType = 2;
                        }
                    }
                    Thread.Sleep(20);
                    if (pathGrid[x, y].tileType == 2)
                    {
                        rNum = r.Next(0, 3);
                        if (x == 0 && y == 0)
                        {
                            pipeGrid[x, y] = new cutPipe(emptyCut, fullCut, _sound, new Rectangle(x_ + (_col * 60), y_ + (_row * 60), 60, 60), rNum, true);
                        }
                        else
                        {
                            pipeGrid[x, y] = new cutPipe(emptyCut, fullCut, _sound, new Rectangle(x_ + (_col * 60), y_ + (_row * 60), 60, 60), rNum, false);
                        }
                    }
                    else if (pathGrid[x, y].tileType == 1)
                    {
                        rNum           = r.Next(0, 3);
                        pipeGrid[x, y] = new strPipe(emptyStr, fullStr, _sound, new Rectangle(x_ + (_col * 60), y_ + (_row * 60), 60, 60), rNum);
                    }
                    else if (pathGrid[x, y].tileType == 0)
                    {
                        rNum           = r.Next(0, 3);
                        pipeGrid[x, y] = new corPipe(emptyCor, fullCor, _sound, new Rectangle(x_ + (_col * 60), y_ + (_row * 60), 60, 60), rNum);
                    }
                    _row += 1;
                }
                _col += 1;
                _row  = 0;
            }
            return(pipeGrid);
        }
Beispiel #42
0
 public GameMap()
 {
     Tiles = BlankTiles();
 }
Beispiel #43
0
        private Tile[,] finishPathGrid(Tile[,] pathGrid, int width, int length)
        {
            int[] currentPos = new int[2];
            int[] prevPos    = new int[2];
            int   currentDir; // 0 = HOR, 1 = VER, 2 = EITHER
            int   nextDir;
            int   dirHolder;  // 0 N, 1 E, 2 S, 3 W

            int[] possibleMoves = new int[4];
            int   possibleSum;
            int   rNum;
            int   pipeType; // 0 = CORNER, 1 = STRAIGHT, 2 = CUTOFF

            while (true)
            {
                pathGrid      = createPathGrid(pathGrid, width, length);
                currentPos[0] = 0;
                currentPos[1] = 0;
                prevPos[0]    = 0;
                prevPos[1]    = 0;
                currentDir    = 2;
                nextDir       = 0;
                dirHolder     = 0;
                possibleMoves = new int[4] {
                    0, 0, 0, 0
                };
                possibleSum = 1;
                rNum        = 0;
                pipeType    = 0;
                Random r = new Random();

                while (possibleSum != 0)
                {
                    Thread.Sleep(10);
                    if (currentPos[0] == (width - 1) && currentPos[1] == (length - 1))
                    {
                        break;
                    }
                    possibleMoves = checkValidMoves(possibleMoves, currentPos, pathGrid, width, length);
                    if (currentPos[1] == 0 && prevPos[1] != 0)
                    {
                        dirHolder = 1;
                    }
                    else if (currentPos[0] == 0 && prevPos[0] != 0)
                    {
                        dirHolder = 2;
                    }
                    else if (currentPos[1] == (length - 1) && prevPos[1] != (length - 1))
                    {
                        dirHolder = 2;
                    }
                    else if (currentPos[0] == (width - 1) && prevPos[0] != (width - 1))
                    {
                        dirHolder = 1;
                    }
                    else
                    {
                        possibleSum = sumPossible(possibleMoves);
                        rNum        = r.Next(0, possibleSum);
                        dirHolder   = checkDirection(possibleMoves, rNum);
                    }

                    if (dirHolder == 0 || dirHolder == 2)
                    {
                        nextDir = 1;
                    }
                    else
                    {
                        nextDir = 0;
                    }

                    if (currentDir == 2)
                    {
                        pipeType = 2;
                    }
                    else if (nextDir == currentDir)
                    {
                        pipeType = 1;
                    }
                    else
                    {
                        pipeType = 0;
                    }
                    pathGrid[currentPos[0], currentPos[1]].tileType = pipeType;
                    pathGrid[currentPos[0], currentPos[1]].valid    = 0;

                    prevPos = currentPos;
                    if (dirHolder == 0)
                    {
                        currentPos[1] -= 1;
                    }
                    else if (dirHolder == 1)
                    {
                        currentPos[0] += 1;
                    }
                    else if (dirHolder == 2)
                    {
                        currentPos[1] += 1;
                    }
                    else
                    {
                        currentPos[0] -= 1;
                    }
                    currentDir = nextDir;
                }
                if (currentPos[0] == (width - 1) && currentPos[1] == (length - 1))
                {
                    break;
                }
            }
            return(pathGrid);
        }
Beispiel #44
0
        public static void LoadFromXML(string filePath)
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(filePath);

            // setup the tile array
            XmlNode tiles = doc.GetElementsByTagName("Tiles")[0];
            int     w     = int.Parse(tiles.Attributes["Width"].Value);
            int     h     = int.Parse(tiles.Attributes["Height"].Value);

            Tiles = new Tile[w, h];

            // Add the tiles
            XmlNodeList tileList = doc.GetElementsByTagName("Tile");

            foreach (XmlNode node in tileList)
            {
                Tile t = Tile.LoadTileFromXml(node);

                Tiles[t.Position.X, t.Position.Y] = t;
            }



            //int currentRow = 0;

            //using(XmlReader reader = XmlReader.Create(filePath))
            //{
            //    reader.MoveToContent();
            //    while(reader.Read())
            //    {
            //        if(reader.IsStartElement())
            //        {
            //            switch(reader.Name.ToUpper())
            //            {
            //                case "TILEMAP":
            //                    break;

            //                case "TILES":
            //                    string width = reader.GetAttribute("Width");
            //                    string height = reader.GetAttribute("Height");

            //                    int w = int.Parse(width);
            //                    int h = int.Parse(height);

            //                    Tiles = new Tile[w, h];

            //                    break;


            //                case "ROW":

            //                    string y = reader.GetAttribute("Y");
            //                    currentRow = int.Parse(y);

            //                    break;

            //                case "TILE":

            //                    string tID = reader.GetAttribute("TextureID");
            //                    int x = int.Parse(reader.GetAttribute("X"));

            //                    //Tiles[x, currentRow] = new Tile(int.Parse(tID), x, currentRow);
            //                    Tiles[x, currentRow] = new Tile(1, x, currentRow);


            //                    break;

            //                case "GameObject":


            //                    break;
            //            }


            //        }
            //    }
            //}
        }
Beispiel #45
0
    void GenerateMap()
    {
        // Locate all tiles in "Tiles" object of scene
        GameObject tiles = GameObject.Find("Tiles");

        _tileMap = new Tile[heightMap.width, heightMap.height];
        for (int i = 0; i < heightMap.height; i++)
        {
            for (int j = 0; j < heightMap.width; j++)
            {
                float height = heightMap.GetPixel(i, j).r;

                // We need bias to arrange hexagons over X axis
                int bias = i % 2 == 0 ? 0 : 5;
                // Spawn tiles (8.66 IS MAGIC NUM HERE)
                float magicNum = 8.66f;
                int   typeIndex;
                if (height == 0f)
                {
                    typeIndex = 0;
                }
                else if (height <= 0.2f)
                {
                    typeIndex = 1;
                }
                else if (height <= 0.4f)
                {
                    typeIndex = 2;
                }
                else if (height <= 0.6f)
                {
                    typeIndex = 3;
                }
                else if (height <= 0.8f)
                {
                    typeIndex = 4;
                }
                else
                {
                    typeIndex = 5;
                }

                GameObject tile = Instantiate(_tilePrefabs[typeIndex],
                                              new Vector3(i * magicNum, height * 10, j * 10 + bias),
                                              new Quaternion(0f, 0f, 0f, 0f));
                tile.transform.parent = tiles.transform;
                // Add Tile properties
                Tile t = tile.AddComponent <Tile>() as Tile;
                t._type             = (Tile.TileTypes)typeIndex + 1; // increment typeIndex by 1 since the first item is Empty in TileTypes
                t._coordinateHeight = i;
                t._coordinateWidth  = j;
                //t._neighborTiles = FindNeighborsOfTile(t);
                // Save Tile object to tilemap
                _tileMap[i, j] = t;
            }
        }
        // Now find neighbours for all tiles
        foreach (Tile t in _tileMap)
        {
            t._neighbourTiles = FindNeighborsOfTile(t);
            HideTileEdges(t);
        }
    }
Beispiel #46
0
        //CHECK VALID POSITIONS
        private int[] checkValidMoves(int[] possibleMoves, int[] currentPos, Tile[,] pathGrid, int width, int length)
        {
            int x = currentPos[0];
            int y = currentPos[1];

            //NORTH
            if (y - 1 < 0)
            {
                possibleMoves[0] = 0;
            }
            else if (pathGrid[x, y - 1].valid == 0)
            {
                possibleMoves[0] = 0;
            }
            else
            {
                possibleMoves[0] = 1;
            }

            //EAST
            if (x + 1 > (width - 1))
            {
                possibleMoves[1] = 0;
            }
            else if (pathGrid[x + 1, y].valid == 0)
            {
                possibleMoves[1] = 0;
            }
            else
            {
                possibleMoves[1] = 1;
            }

            //SOUTH
            if (y + 1 > (length - 1))
            {
                possibleMoves[2] = 0;
            }
            else if (pathGrid[x, y + 1].valid == 0)
            {
                possibleMoves[2] = 0;
            }
            else
            {
                possibleMoves[2] = 1;
            }

            //WEST
            if (x - 1 < 0)
            {
                possibleMoves[3] = 0;
            }
            else if (pathGrid[x - 1, y].valid == 0)
            {
                possibleMoves[3] = 0;
            }
            else
            {
                possibleMoves[3] = 1;
            }

            return(possibleMoves);
        }
Beispiel #47
0
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            font = Content.Load <SpriteFont>("mainFont");

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            //GUI content----------------------------------------------------------------------------------//
            towerGraphs             = new GUI_Anim[30];
            enemyGraphs             = new GUI_Anim[75];
            towerGraphsPlaceholders = new GUI_Anim[2];


            //font
            font = Content.Load <SpriteFont>("Arial"); //TEMP FONT

            //menu screen
            Texture2D menuImage = Content.Load <Texture2D>("GUI_Assets/menuscreen.png");

            menuScreen = new GUI_StatGraphics(menuImage, new Point(750, 600), 1, 1, 1, new Vector2(0, 0));

            //how to
            Texture2D howToImg1 = Content.Load <Texture2D>("GUI_Assets/htp1.png");

            howTo1 = new GUI_StatGraphics(howToImg1, new Point(600, 400), 1, 1, 1, new Vector2(75, 50));
            Texture2D howToImg2 = Content.Load <Texture2D>("GUI_Assets/htp2.png");

            howTo2 = new GUI_StatGraphics(howToImg2, new Point(600, 400), 1, 1, 1, new Vector2(75, 50));

            //map
            Texture2D mapImage    = Content.Load <Texture2D>("GUI_Assets/mapassets3type.png");
            Texture2D mapOverlay1 = Content.Load <Texture2D>("GUI_Assets/lv1_overlay.png");

            mapGraph  = new GUI_StatGraphics(mapImage, mapOverlay1, new Point(150, 50), 3, 1, 3, "newExampleMap1.txt");
            mapGraph2 = new GUI_StatGraphics(mapImage, mapOverlay1, new Point(150, 50), 3, 1, 3, "FinalExampleMap2.txt");

            //tower
            towerImage  = Content.Load <Texture2D>("GUI_Assets/towerplaceholder");
            lancerImage = Content.Load <Texture2D>("GUI_Assets/lancer");
            //enemy
            enemyImage = Content.Load <Texture2D>("GUI_Assets/enemyplaceholder");
            beeImage   = Content.Load <Texture2D>("GUI_Assets/bees");

            towerGraphsPlaceholders[0] = new GUI_Anim(towerImage, new Point(100, 150), 6, 3, 2, 1000, 0);
            towerGraphsPlaceholders[1] = new GUI_Anim(lancerImage, new Point(100, 150), 6, 3, 2, 1000, 0);


            //listing
            Texture2D listingImage = Content.Load <Texture2D>("GUI_Assets/storelistingplaceholder");

            listing1 = new GUI_StatGraphics(listingImage, new Point(150, 150), 1, 1, 1, new Vector2(450, 500));
            listing2 = new GUI_StatGraphics(listingImage, new Point(150, 150), 1, 1, 1, new Vector2(550, 500));
            listing3 = new GUI_StatGraphics(listingImage, new Point(150, 150), 1, 1, 1, new Vector2(650, 500));
            //store
            Texture2D backStoreImage = Content.Load <Texture2D>("GUI_Assets/storebackplaceholder");

            storeBack = new GUI_StatGraphics(backStoreImage, new Point(750, 100), 1, 1, 1, new Vector2(0, 500));
            //bought
            Texture2D boughtImage = Content.Load <Texture2D>("GUI_Assets/bought");

            boughtSym = new GUI_Anim(boughtImage, new Point(25, 25), 1, 1, 1, 1, 0);

            #region Load Map 1
            StreamReader load1 = new StreamReader("newExampleMap1.txt");
            string       line1;
            int          tile1Row    = 0;
            int          tile1Column = 0;
            level1Tiles   = new int[10, 15];
            level1MapTile = new Tile[10, 15];
            while ((line1 = load1.ReadLine()) != null)
            {
                if (line1 == "")//ignores the \n commands to split up rows in the array
                {
                    continue;
                }
                else
                {
                    char[] rowTiles = line1.ToCharArray();
                    foreach (char tile in rowTiles)
                    {
                        int    type    = 0;
                        string tileStr = tile.ToString();
                        int.TryParse(tileStr, out type);
                        level1Tiles[tile1Row, tile1Column] = type;
                        tile1Column++;
                    }
                    tile1Row++;
                    if (tile1Row > 9) //autobreaks if the loop exceeds number of rows in array
                    {
                        break;
                    }
                    tile1Column = 0;
                }
            }


            //converts recieved int array into tile array
            for (int row = 0; row < level1Tiles.GetLength(0); row++)
            {
                for (int column = 0; column < level1Tiles.GetLength(1); column++)
                {
                    level1MapTile[row, column] = new Tile(row, column, 50, 50, level1Tiles[row, column]);
                }
            }

            //finds the start tile for the enemies
            foreach (Tile obj in level1MapTile)
            {
                if (obj.TileValue == 2)
                {
                    startTile1 = obj;
                }
            }


            // values for first stage
            if (level == 1)
            {
                enemyNum = (level + 1) * 10 / 2;
                money    = 1000;
            }
            #endregion

            #region Load Map 2
            StreamReader load2 = new StreamReader("FinalExampleMap2.txt");
            string       line2;
            int          tile2Row    = 0;
            int          tile2Column = 0;
            level2Tiles   = new int[10, 15];
            level2MapTile = new Tile[10, 15];
            while ((line2 = load2.ReadLine()) != null)
            {
                if (line2 == "")//ignores the \n commands to split up rows in the array
                {
                    continue;
                }
                else
                {
                    char[] rowTiles = line2.ToCharArray();
                    foreach (char tile in rowTiles)
                    {
                        int    type    = 0;
                        string tileStr = tile.ToString();
                        int.TryParse(tileStr, out type);
                        level2Tiles[tile2Row, tile2Column] = type;
                        tile2Column++;
                    }
                    tile2Row++;
                    if (tile2Row > 9) //autobreaks if the loop exceeds number of rows in array
                    {
                        break;
                    }
                    tile2Column = 0;
                }
            }
            //converts recieved int array into tile array
            for (int row = 0; row < level2Tiles.GetLength(0); row++)
            {
                for (int column = 0; column < level2Tiles.GetLength(1); column++)
                {
                    level2MapTile[row, column] = new Tile(row, column, 50, 50, level2Tiles[row, column]);
                }
            }

            //finds the start tile for the enemies
            foreach (Tile obj in level2MapTile)
            {
                if (obj.TileValue == 2)
                {
                    startTile2 = obj;
                }
            }

            #endregion
        }
Beispiel #48
0
        /// <summary>
        /// Initializes the CellType map with mission data.
        /// </summary>
        public CellTypeMap(Map map, MissionVariant variant)
        {
            uint mapWidth  = map.GetWidthInTiles();
            uint mapHeight = map.GetHeightInTiles();

            m_Grid = new Tile[mapWidth, mapHeight];

            // Default CellTypes to map CellTypes
            for (uint x = 0; x < mapWidth; ++x)
            {
                for (uint y = 0; y < mapHeight; ++y)
                {
                    m_Grid[x, y].cellType = (CellType)map.GetCellType(x, y);
                }
            }

            // Loop through all units, walls, and tubes
            foreach (PlayerData player in variant.players)
            {
                // Get structure modifications
                foreach (UnitData unit in player.resources.units)
                {
                    if (!StructureData.IsStructure(unit.typeID))
                    {
                        continue;
                    }

                    RectInt area = StructureData.GetStructureArea(new Vector2Int(unit.position.x - 1, unit.position.y - 1), unit.typeID);

                    // Add bulldozed area
                    area.min -= Vector2Int.one;
                    area.max += Vector2Int.one;

                    SetAreaCellType(area, CellType.DozedArea, false);

                    // Add structure tubes
                    if (StructureData.HasTubes(unit.typeID))
                    {
                        m_Grid[unit.position.x - 1, area.max.y - 1].cellType = CellType.Tube0;
                        m_Grid[area.max.x - 1, unit.position.y - 1].cellType = CellType.Tube0;
                    }

                    // Remove bulldozed area
                    area.min += Vector2Int.one;
                    area.max -= Vector2Int.one;

                    SetAreaCellType(area, CellType.DozedArea, true);
                }

                // Get wall tube modifications
                foreach (WallTubeData wallTube in player.resources.wallTubes)
                {
                    CellType cellType = CellType.zPad20;

                    switch (wallTube.typeID)
                    {
                    case DotNetMissionSDK.map_id.Tube:                      cellType = CellType.Tube0;                      break;

                    case DotNetMissionSDK.map_id.Wall:                      cellType = CellType.NormalWall;         break;

                    case DotNetMissionSDK.map_id.LavaWall:          cellType = CellType.LavaWall;           break;

                    case DotNetMissionSDK.map_id.MicrobeWall:       cellType = CellType.MicrobeWall;        break;
                    }

                    m_Grid[wallTube.position.x - 1, wallTube.position.y - 1].cellType = cellType;
                }
            }             // foreach playerStates
        }
        //should each stoplight be its own mapobject
        //its extra things to add to our draw list then
        private void AddIntersection(List <Intersection> intersectionList, Tile[,] tileGrid, ShrunkNode[,] shrunkMap, int shrunkX, int shrunkY, Point expandedPoint, Random rndExtras, int id)
        {
            Intersection intersection = new Intersection(rndExtras, expandedPoint.X, expandedPoint.Y, id);

            MapObject mapObject;

            Dictionary <Direction, StopLight> stopLightList = new Dictionary <Direction, StopLight>();
            int       tileX;
            int       tileY;
            StopLight stopLight;

            int stageLeftRight = rndExtras.Next(0, 1) * 2;  //should always be 0 or 2
            int stageUpDown;

            if (stageLeftRight == 0)
            {
                stageUpDown = 2;
            }
            else
            {
                stageUpDown = 0;
            }


            //Road Down
            if (ShrunkWorldBuilder.IsRoad(new Point(shrunkX, shrunkY + 1), shrunkMap))
            {
                tileX     = expandedPoint.X;
                tileY     = expandedPoint.Y + 1;
                stopLight = new StopLight(0, stageUpDown, intersection, 0);
                stopLightList.Add(Direction.DOWN, stopLight);
                mapObject = new MapObject(stopLight, tileX, tileY, Color.White, 1f);
                tileGrid[tileX, tileY].AddMapObject(mapObject, false, false, true, null, false);
                AddWhiteLine(tileGrid, tileX, tileY, 3);
            }

            // Road Right
            if (ShrunkWorldBuilder.IsRoad(new Point(shrunkX + 1, shrunkY), shrunkMap))
            {
                tileX     = expandedPoint.X + 1;
                tileY     = expandedPoint.Y + 1;
                stopLight = new StopLight(6, stageLeftRight, intersection, 3);
                stopLightList.Add(Direction.RIGHT, stopLight);
                mapObject = new MapObject(stopLight, tileX, tileY, Color.White, 1f);
                tileGrid[tileX, tileY].AddMapObject(mapObject, false, false, true, null, false);
                AddWhiteLine(tileGrid, tileX, tileY, 2);
            }

            // Road Up
            if (ShrunkWorldBuilder.IsRoad(new Point(shrunkX, shrunkY - 1), shrunkMap))
            {
                tileX = expandedPoint.X + 1;
                tileY = expandedPoint.Y;

                stopLight = new StopLight(4, stageUpDown, intersection, 2);
                stopLightList.Add(Direction.UP, stopLight);
                mapObject = new MapObject(stopLight, tileX, tileY, Color.White, 1f);
                tileGrid[tileX, tileY].AddMapObject(mapObject, false, false, true, null, false);
                AddWhiteLine(tileGrid, tileX, tileY, 1);
            }

            //Road Left
            if (ShrunkWorldBuilder.IsRoad(new Point(shrunkX - 1, shrunkY), shrunkMap))
            {
                tileX = expandedPoint.X;
                tileY = expandedPoint.Y;

                stopLight = new StopLight(2, stageLeftRight, intersection, 1);
                stopLightList.Add(Direction.LEFT, stopLight);
                mapObject = new MapObject(stopLight, tileX, tileY, Color.White, 1f);
                tileGrid[tileX, tileY].AddMapObject(mapObject, false, false, true, null, false);
                AddWhiteLine(tileGrid, tileX, tileY, 0);
            }

            AddTurningArrows(tileGrid, expandedPoint, 0);

            intersection.SetStopLightList(stopLightList);
            intersectionList.Add(intersection);
        }
Beispiel #50
0
        private static void GameTest2()
        {
            string json = File.ReadAllText(
                @"D:\CS\djikstra-problem\json-exports\strategy-game-export-2.json",
                Encoding.UTF8);

            Tile[,] tiles = GameFunctions.GetTiles(json);
            int rows = Util.GetRows(tiles);
            int cols = Util.GetCols(tiles);

            Unit[,] board = new Unit[rows, cols];

            Unit playerUnit1 = new Unit(
                UnitTypes.Soldier,
                3,
                new Stats(10, 100),
                new Coordinate(0, 1),
                "player-unit-1",
                Teams.Player,
                ref board,
                tiles);

            Unit playerUnit2 = new Unit(
                UnitTypes.Soldier,
                3,
                new Stats(10, 100),
                new Coordinate(1, 1),
                "player-unit-2",
                Teams.Player,
                ref board,
                tiles);

            Unit playerUnit3 = new Unit(
                UnitTypes.Soldier,
                3,
                new Stats(10, 100),
                new Coordinate(2, 1),
                "player-unit-3",
                Teams.Player,
                ref board,
                tiles);

            Unit playerUnit4 = new Unit(
                UnitTypes.Soldier,
                3,
                new Stats(10, 100),
                new Coordinate(1, 2),
                "player-unit-4",
                Teams.Player,
                ref board,
                tiles);

            Unit enemyUnit1 = new Unit(
                UnitTypes.Seaman,
                5,
                new Stats(30, 70),
                new Coordinate(1, 6),
                "enemy-unit-1",
                Teams.Enemy,
                ref board,
                tiles);

            Unit enemyUnit2 = new Unit(
                UnitTypes.Seaman,
                5,
                new Stats(30, 70),
                new Coordinate(2, 6),
                "enemy-unit-2",
                Teams.Enemy,
                ref board,
                tiles);

            Unit enemyUnit3 = new Unit(
                UnitTypes.Seaman,
                5,
                new Stats(30, 70),
                new Coordinate(3, 6),
                "enemy-unit-3",
                Teams.Enemy,
                ref board,
                tiles);

            Unit enemyUnit4 = new Unit(
                UnitTypes.Seaman,
                5,
                new Stats(30, 70),
                new Coordinate(2, 5),
                "enemy-unit-4",
                Teams.Enemy,
                ref board,
                tiles);

            Unit enemyUnit5 = new Unit(
                UnitTypes.Seaman,
                5,
                new Stats(30, 70),
                new Coordinate(3, 5),
                "enemy-unit-5",
                Teams.Enemy,
                ref board,
                tiles);

            List <Unit> playerUnits = new List <Unit>();
            List <Unit> enemyUnits  = new List <Unit>();

            playerUnits.Add(playerUnit1);
            playerUnits.Add(playerUnit2);
            playerUnits.Add(playerUnit3);
            playerUnits.Add(playerUnit4);

            enemyUnits.Add(enemyUnit1);
            enemyUnits.Add(enemyUnit2);
            enemyUnits.Add(enemyUnit3);
            enemyUnits.Add(enemyUnit4);
            enemyUnits.Add(enemyUnit5);

            Game game = new Game(board, tiles, playerUnits, enemyUnits);

            game.PlayGame();
        }
Beispiel #51
0
 void Start()
 {
     m_allTiles = new Tile[width, height];
     SetupTiles();
     SetupCamera();
 }
 private void AddWhiteLine(Tile[,] tileGrid, int tileX, int tileY, int tileIndex)
 {
     tileGrid[tileX, tileY].AddLayer(GroundLayerController.GetLayerByIndex(LayerType.ROADDECALS, tileIndex));
 }
Beispiel #53
0
    /// <summary>
    /// Generates the basic walls, floor, and entrance for any building.
    /// Picks the exact position of entrance, and returns it
    /// </summary>
    /// <param name="width"></param>
    /// <param name="height"></param>
    /// <param name="buildingObjects">Building objects to be filled with walls</param>
    /// <param name="buildTiles"></param>
    /// <param name="entranceID"></param>
    /// <param name="style"></param>
    /// <returns></returns>
    public static Vec2i GenerateWallsFloorAndEntrance(int width, int height, WorldObjectData[,] buildingObjects,
                                                      Tile[,] buildTiles, int entranceID, BuildingStyle style, int entraceDis = -1, WorldObjectData wallType = null, Tile tileType = null)
    {
        int entWidth = 2;

        if (entraceDis == -1)
        {
            if (entranceID == NORTH_ENTRANCE || entranceID == SOUTH_ENTRANCE)
            {
                entraceDis = MiscMaths.RandomRange(1, width - 1);
            }
            else
            {
                entraceDis = MiscMaths.RandomRange(1, height - 1);
            }
        }

        //Decide the position of the entrance
        Vec2i entrance = null;

        if (entranceID == NORTH_ENTRANCE)
        {
            entrance = new Vec2i(entraceDis, height - 1);
        }
        else if (entranceID == SOUTH_ENTRANCE)
        {
            entrance = new Vec2i(entraceDis, 0);
        }
        else if (entranceID == EAST_ENTRANCE)
        {
            entrance = new Vec2i(width - 1, entraceDis);
        }
        else if (entranceID == WEST_ENTRANCE)
        {
            entrance = new Vec2i(0, entraceDis);
        }


        //Assign correct wall type if none given
        if (wallType == null)
        {
            switch (style)
            {
            case BuildingStyle.stone:
                wallType = new BrickWall(new Vec2i(0, 0));
                break;

            case BuildingStyle.wood:
                //TODO - Add
                wallType = new BrickWall(new Vec2i(0, 0));
                break;
            }
        }//Asign correct tile type if none given
        if (tileType == null)
        {
            switch (style)
            {
            case BuildingStyle.stone:
                tileType = Tile.STONE_FLOOR;
                break;

            case BuildingStyle.wood:
                tileType = Tile.WOOD_FLOOR;
                break;
            }
        }
        //Iterate all points
        for (int x = 0; x < width; x++)
        {
            for (int z = 0; z < height; z++)
            {
                //Asign tile
                buildTiles[x, z] = tileType;
                if (x == 0 || x == width - 1 || z == 0 || z == height - 1)
                {
                    //Asign wall if no entrance
                    if (!(entrance.x == x & entrance.z == z))
                    {
                        if (x == 3)
                        {
                            buildingObjects[x, z] = new BuildingWall(new Vec2i(0, 0), "brick", 5,
                                                                     new GlassWindow(new Vec2i(0, 0), new Vec2i(0, 1)), 2);
                        }
                        else
                        {
                            buildingObjects[x, z] = new BuildingWall(new Vec2i(0, -1), "brick", 5);
                        }
                    }
                }
            }
        }
        //(buildingObjects[0, 0] as BuildingWall).AddRoof(new Roof(new Vec2i(0, 0), new Vec2i(width, height)));

        return(entrance);
    }
Beispiel #54
0
 public MapGeneratedEvent(RoutedEvent routedEvent, Tile[,] map) : base(routedEvent)
 {
     Map = map;
 }
Beispiel #55
0
    // creating a 2D grid to be handled by the CombatManager


    public void InitializeGrid()
    {
        // assuming all tiles ave a size of 1;
        float size = 1f;
        int   minX = 1000;
        int   maxX = -1000;
        int   minY = 1000;
        int   maxY = -1000;

        for (int i = 0; i < transform.childCount; i++)
        {
            Vector3 v = transform.GetChild(i).transform.position;
            if (v.x < minX)
            {
                minX = (int)v.x;
            }
            if (v.x > maxX)
            {
                maxX = (int)v.x;
            }
            if (v.z < minY)
            {
                minY = (int)v.z;
            }
            if (v.z > maxY)
            {
                maxY = (int)v.z;
            }
        }

        // set parent to position (minX,0,minY) so that other tile coordinates may be accessed relatively to gameobject
        GameObject tmp = new GameObject();

        while (transform.childCount != 0)
        {
            transform.GetChild(0).SetParent(tmp.transform);
        }
        gameObject.transform.position = new Vector3(minX, 0, minY);
        while (tmp.transform.childCount != 0)
        {
            tmp.transform.GetChild(0).SetParent(transform);
        }
        DestroyImmediate(tmp);

        column = (int)((maxX - minX) / size) + 1; // going from the minX to the maxX included
        row    = (int)((maxY - minY) / size) + 1;
        //Debug.Log("column: " + column + " row: " + row);
        grid = new Tile[column, row];
        // initilyzing the grid
        for (int i = 0; i < column; i++)
        {
            for (int j = 0; j < row; j++)
            {
                grid[i, j] = null;
            }
        }

        for (int i = 0; i < transform.childCount; i++)
        {
            Vector3 v = transform.GetChild(i).transform.position;
            Tile    t = new Tile();
            // get the obstacle if there is one
            t.posX = (int)((v.x - minX) / size);
            t.posY = (int)((v.z - minY) / size);
            grid[t.posX, t.posY] = t;
            //Debug.Log(transform.GetChild(i).transform.localPosition + " converted to " + t.posX + " " + t.posY);
        }
    }
Beispiel #56
0
        private SwinGameSDK.Vector GetDistractionVector(SwinGameSDK.Point2D playerPos, Tile[,] tileSet, SwinGameSDK.Vector currentMoveVector)
        {
            SwinGameSDK.Vector  distractionVector = new SwinGameSDK.Vector();
            SwinGameSDK.Point2D max = new Point2D();
            SwinGameSDK.Point2D min = new Point2D();


            if (currentMoveVector.Angle <= 0)
            {
                min.Y = playerPos.Y + (currentMoveVector.Y * 7);
                max.Y = playerPos.Y;
            }
            else
            {
                max.Y = playerPos.Y - (currentMoveVector.Y * 7);
                min.Y = playerPos.Y;
            }

            if (currentMoveVector.Angle < 90 && currentMoveVector.Angle > -90)
            {
                max.X = playerPos.X + (currentMoveVector.X * 7);
                min.X = playerPos.X;
            }
            else
            {
                min.X = playerPos.X - (currentMoveVector.X * 7);
                max.X = playerPos.X;
            }

            float normalX = SwinGame.VectorNormal(currentMoveVector).X *(12);
            float normalY = SwinGame.VectorNormal(currentMoveVector).Y *(12);

            int iMax = (int)(Math.Ceiling(max.X / 60) + 1);
            int iMin = (int)(Math.Floor(min.X / 60) - 1);
            int jMax = (int)(Math.Ceiling(max.Y / 60) + 1);
            int jMin = (int)(Math.Floor(min.Y / 60) - 1);

            if (iMax > Game.x_width - 1)
            {
                iMax = Game.x_width - 1;
            }
            if (iMin < 0)
            {
                iMin = 0;
            }
            if (jMax > Game.y_height - 1)
            {
                jMax = Game.y_height - 1;
            }
            if (jMin < 0)
            {
                jMin = 0;
            }

            //loops through each square in the min/max of the rect fov.
            for (int i = iMin; i < iMax; i++)
            {
                for (int j = jMin; j < jMax; j++)
                {
                    if (tileSet[i, j].GetTileType() == TileType.WALL)
                    {
                        // I'm so sorry. It's so ugly.
                        if
                        (
                            SwinGame.LineIntersectsRect(SwinGame.LineFrom(playerPos.X + normalX, playerPos.Y + normalY, playerPos.X + (currentMoveVector.X * 7) + normalX, playerPos.Y + (currentMoveVector.Y * 7) + normalY), tileSet[i, j].GetHitBox())
                            ||
                            SwinGame.LineIntersectsRect(SwinGame.LineFrom(playerPos.X - normalX, playerPos.Y - normalY, playerPos.X + (currentMoveVector.X * 7) - normalX, playerPos.Y + (currentMoveVector.Y * 7) - normalY), tileSet[i, j].GetHitBox())
                        )
                        {
                            SwinGameSDK.Vector thisDistraction = new SwinGameSDK.Vector();

                            float distance = SwinGame.PointPointDistance(playerPos, tileSet[i, j].GetPos());
                            if (distance < 0)
                            {
                                distance = 0;
                            }

                            thisDistraction = SwinGame.VectorFromAngle(SwinGame.CalculateAngleBetween(playerPos, tileSet[i, j].GetPos()), distance);

                            distractionVector = SwinGame.AddVectors(distractionVector, SwinGame.InvertVector(thisDistraction));
                        }
                    }
                }
            }

            if (distractionVector.Magnitude > 3)
            {
                distractionVector = SwinGame.LimitVector(distractionVector, 3);
            }

            return(distractionVector);
        }
Beispiel #57
0
        public void LoadContent(ContentManager content)
        {
            SpawnGroupValues = new double[10];
            DrawTiles        = new Tile[(int)MapSize.X, (int)MapSize.Y];
            SpawnTiles       = new List <Vector2>();
            LightList        = new List <Light>();

            for (int i = 0; i < 10; i++)
            {
                SpawnGroupValues[i] = Random.NextDouble();
            }

            for (int x = 0; x < (int)MapSize.X; x++)
            {
                for (int y = 0; y < (int)MapSize.Y; y++)
                {
                    switch (Tiles[x, y])
                    {
                    case TileType.Spawn:
                    {
                        SpawnTiles.Add(new Vector2(x, y));
                    }
                    break;

                    case TileType.Solid:
                    {
                        float against, valu;
                        against = 0;
                        valu    = 100;

                        if (ProbabilityMap != null)
                        {
                            against = (float)Random.NextDouble();
                            valu    = ProbabilityMap[x, y] / 100f;

                            if (SpawnGroup[x, y] != 0)
                            {
                                against = (float)SpawnGroupValues[SpawnGroup[x, y]];
                            }
                        }

                        if (valu >= against)
                        {
                            Tile drawTile = new Tile()
                            {
                                Size     = TileSize,
                                Position = new Vector2(x * TileSize.X, y * TileSize.Y)
                            };
                            drawTile.Index = new Vector2(x, y);
                            drawTile.LoadContent(content);

                            DrawTiles[x, y] = drawTile;
                        }
                        else
                        {
                            Tiles[x, y] = TileType.Empty;
                        }
                    }
                    break;

                    case TileType.BouncePad:
                    {
                        Tile drawTile = new Tile()
                        {
                            Size     = TileSize,
                            Position = new Vector2(x * TileSize.X, y * TileSize.Y),
                            Color    = Color.Red
                        };
                        drawTile.Index = new Vector2(x, y);
                        drawTile.LoadContent(content);

                        DrawTiles[x, y] = drawTile;
                    }
                    break;
                    }
                }
            }
        }
Beispiel #58
0
 // -------------------- Constructor --------------------
 public PathFactory(Tile[,] TilesArray)
 {
     this.map = TilesArray;
 }
Beispiel #59
0
 public Shape(Tile[,] tiles, Vector2 position)
 {
     this.tiles    = tiles;
     this.position = position;
 }
Beispiel #60
0
 public abstract void Init(System.Object data, Tile[,] tilesStandingOn);