/// <summary> /// Just a quick and dirty method for generating any object in our Tiled map that has a corresponding entity definition /// in an XML file. /// </summary> public List<IGameObject> GenerateXMLEnvironmentObjectsFromTiled(Map map, TileLayer layer) { List<IGameObject> gameObjects = new List<IGameObject>(); for (int i = 0; i < layer.Width; i++) { for (int j = 0; j < layer.Height; j++) { if (layer.Tiles[i, j] != null) { IGameObject gameObject = rawPool.New(); gameObject.Position = new Vector2(map.TileWidth * i, map.TileHeight * j); //Load in the correct element from the entity definitions file. string objectName = layer.Tiles[i, j].Properties["name"].RawValue; if (xmlDoc.Root != null) { List<XElement> elements = (xmlDoc.Root.Elements("entity") .Where(el => (string)el.Attribute("name") == objectName)).ToList(); //We'll let the IRenderableComponent build itself but before finishing it off we'll swap the texture, so just //generate all the components via the Tiled file... if (elements.Count > 0) GenerateComponents(gameObject, elements[0]); } //And then swap the texture with the one from Tiled... IRenderComponent renderComponent = gameObject.GetComponent<IRenderComponent>(); if (renderComponent != null) { ITexturedRenderable renderable = (ITexturedRenderable)renderComponent.GetRenderable(0); if (renderable != null) { renderable.AssetName = layer.Tiles[i, j].Properties["texture"].RawValue; renderComponent.Load(content); renderComponent.SetLayer(1f); } } FireOnGameObjectCreated(gameObject); gameObjects.Add(gameObject); gameObject.Initialize(); } } } return gameObjects; }
/// <summary> /// Draws an area of the map defined in world space (pixel) coordinates. /// </summary> /// <param name="spriteBatch">The SpriteBatch to use to render the map.</param> /// <param name="worldArea">The area of the map to draw in world coordinates.</param> public void Draw(SpriteBatch spriteBatch, Rectangle worldArea) { if (spriteBatch == null) { throw new ArgumentNullException("spriteBatch"); } if (Orientation == Orientation.Orthogonal) { // figure out the min and max tile indices to draw int minX = Math.Max((int)Math.Floor((float)worldArea.Left / TileWidth), 0); int maxX = Math.Min((int)Math.Ceiling((float)worldArea.Right / TileWidth), WidthInTiles); int minY = Math.Max((int)Math.Floor((float)worldArea.Top / TileHeight), 0); int maxY = Math.Min((int)Math.Ceiling((float)worldArea.Bottom / TileHeight), HeightInTiles); foreach (var l in Layers) { if (!l.Visible) { continue; } TileLayer tileLayer = l as TileLayer; if (tileLayer != null) { for (int x = minX; x < maxX; x++) { for (int y = minY; y < maxY; y++) { Tile tile = tileLayer.Tiles[x, y]; if (tile == null) { continue; } Rectangle r = new Rectangle(x * TileWidth, y * TileHeight - tile.Source.Height + TileHeight, tile.Source.Width, tile.Source.Height); tile.DrawOrthographic(spriteBatch, r, tileLayer.Opacity, l.LayerDepth); } } } } } else { throw new NotSupportedException("TiledLib does not have built in support for rendering isometric tile maps."); } }
public bool?CheckCollision(Vector2 position) { for (int i = 0; i < Layers.Count; i++) { if (!Layers[i].Properties.Contains("Collision")) { continue; } TileLayer tileLayer = Layers[i] as TileLayer; position.X = (int)position.X; position.Y = (int)position.Y; Vector2 tilePosition = new Vector2((int)(position.X / TileWidth), (int)(position.Y / TileHeight)); if (tilePosition.X < 0 || tilePosition.Y < 0 || tilePosition.X > Width - 1 || tilePosition.Y > Height - 1) { continue; } Tile collisionTile = tileLayer.Tiles[(int)tilePosition.X, (int)tilePosition.Y]; if (collisionTile == null) { continue; } if (collisionTile.CollisionData != null) { int positionOnTileX = ((int)position.X - (((int)position.X / TileWidth) * TileWidth)); int positionOnTileY = ((int)position.Y - (((int)position.Y / TileHeight) * TileHeight)); positionOnTileX = (int)MathHelper.Clamp(positionOnTileX, 0, TileWidth); positionOnTileY = (int)MathHelper.Clamp(positionOnTileY, 0, TileHeight); int pixelCheckX = (collisionTile.Source.X) + positionOnTileX; int pixelCheckY = (collisionTile.Source.Y) + positionOnTileY; return(collisionTile.CollisionData[(pixelCheckY * collisionTile.Texture.Width) + pixelCheckX]); } else { continue; } } return(null); }
/// <summary> /// Draws a single layer as shadows, by layer name /// </summary> /// <param name="spriteBatch">The SpriteBatch to use to render the layer.</param> /// <param name="layerName">The name of the layer to draw.</param> /// <param name="gameCamera">The camera to use for positioning.</param> /// <param name="shadowOffset">Pixel amount to offset the shadowing by.</param> /// <param name="alpha">Shadow opacity</param> //public void DrawLayer(SpriteBatch spriteBatch, string layerName, Camera gameCamera, Vector2 shadowOffset, float alpha) //{ // var l = GetLayer(layerName); // if (l == null) // return; // if (!l.Visible) // return; // TileLayer tileLayer = l as TileLayer; // if (tileLayer != null) // { // //for (float mult = 0f; mult < 1f; mult += 0.1f) // //{ // DrawLayer(spriteBatch, l, gameCamera, shadowOffset, alpha, Color.Black, false); // //DrawLayer(spriteBatch, l, gameCamera, shadowOffset, alpha, Color.Black); // //} // //DrawLayer(spriteBatch, l, gameCamera, shadowOffset * 0.5f, alpha * 0.75f, Color.Black); // //DrawLayer(spriteBatch, l, gameCamera, shadowOffset * 0.75f, alpha * 0.5f, Color.Black); // //DrawLayer(spriteBatch, l, gameCamera, shadowOffset, alpha *0.25f, Color.Black); // } //} /// <summary> /// Draws a single layer of the map /// </summary> /// <param name="spriteBatch">The SpriteBatch to use to render the layer.</param> /// <param name="tileLayer">The layer to draw.</param> /// <param name="gameCamera">The camera to use for positioning.</param> /// <param name="offset">A pixel amount to offset the tile positioning by</param> /// <param name="alpha">Layer opacity.</param> /// <param name="color">The color to use when drawing.</param> public void DrawLayer(SpriteBatch spriteBatch, Layer layer, Camera gameCamera, Color color, bool silhouette, float scale) { if (!layer.Visible) { return; } TileLayer tileLayer = layer as TileLayer; if (tileLayer != null) { Rectangle worldArea = new Rectangle((int)gameCamera.Position.X - (int)(((float)gameCamera.Width * 2f) / scale), (int)gameCamera.Position.Y - (int)(((float)gameCamera.Height * 2) / scale), (int)((gameCamera.Width * 4) / scale), (int)((gameCamera.Height * 4) / scale)); //Rectangle worldArea = new Rectangle(0, (int)gameCamera.Position.Y - (int)(((float)gameCamera.Height) * (2f-scale)), TileWidth * Width, (int)(((float)gameCamera.Height*2 ) * (3f-(2f*scale)))); // figure out the min and max tile indices to draw int minX = Math.Max((int)Math.Floor((float)worldArea.Left / TileWidth), 0); int maxX = Math.Min((int)Math.Ceiling((float)worldArea.Right / TileWidth), Width); int minY = Math.Max((int)Math.Floor((float)worldArea.Top / TileHeight), 0); int maxY = Math.Min((int)Math.Ceiling((float)worldArea.Bottom / TileHeight), Height); for (int x = minX; x < maxX; x++) { for (int y = minY; y < maxY; y++) { //if ((new Vector2((x * TileWidth) + (TileWidth / 2), (y * TileHeight) + (TileHeight / 2)) - new Vector2(worldArea.Center.X, worldArea.Center.Y)).Length() < gameCamera.Width * 0.75) //{ Tile tile = tileLayer.Tiles[x, y]; if (tile == null) { continue; } // - tile.Source.Height + TileHeight; Rectangle r = new Rectangle(x * TileWidth, y * TileHeight, tile.Source.Width, tile.Source.Height); spriteBatch.Draw(!silhouette ? tile.Texture : tile.WhiteTexture, r, tile.Source, color); //} } } } }
/// <summary> /// Draws a single layer of the map /// </summary> /// <param name="spriteBatch">The SpriteBatch to use to render the layer.</param> /// <param name="tileLayer">The layer to draw.</param> /// <param name="gameCamera">The camera to use for positioning.</param> /// <param name="offset">A pixel amount to offset the tile positioning by</param> /// <param name="alpha">Layer opacity.</param> /// <param name="color">The color to use when drawing.</param> public void DrawLayer(SpriteBatch spriteBatch, Layer layer, Camera gameCamera, Vector2 offset, float alpha, Color color) { if (!layer.Visible) { return; } TileLayer tileLayer = layer as TileLayer; if (tileLayer != null) { Rectangle worldArea = new Rectangle((int)gameCamera.Position.X - (gameCamera.Width + 200), (int)gameCamera.Position.Y - (int)(gameCamera.Height * 1.5), (gameCamera.Width * 2) + 400, gameCamera.Height * 3); // figure out the min and max tile indices to draw int minX = Math.Max((int)Math.Floor((float)worldArea.Left / TileWidth), 0); int maxX = Math.Min((int)Math.Ceiling((float)worldArea.Right / TileWidth), Width); int minY = Math.Max((int)Math.Floor((float)worldArea.Top / TileHeight), 0); int maxY = Math.Min((int)Math.Ceiling((float)worldArea.Bottom / TileHeight), Height); for (int x = minX; x < maxX; x++) { for (int y = minY; y < maxY; y++) { //if ((new Vector2((x * TileWidth) + (TileWidth/2), (y * TileHeight) + (TileHeight/2)) - new Vector2(worldArea.Center.X, worldArea.Center.Y)).Length() < gameCamera.Width * 3f) //{ Tile tile = tileLayer.Tiles[x, y]; if (tile == null) { continue; } // - tile.Source.Height + TileHeight; Rectangle r = new Rectangle(x * TileWidth, y * TileHeight, tile.Source.Width, tile.Source.Height); spriteBatch.Draw(tile.Texture, r, tile.Source, color); //} } } } }
static void WriteCSV(this XmlWriter writer, TileLayer layer) { writer.WriteRaw(Environment.NewLine); var sb = new StringBuilder(layer.Width * 4); for (int y = 0, i = 0; y < layer.Height; y++) { sb.Clear(); for (int x = 0; x < layer.Width; x++, i++) { sb.Append(layer.Data[i]); sb.Append(','); } if (y + 1 == layer.Height) { sb.Length--; } sb.AppendLine(); writer.WriteRaw(sb.ToString()); } }
public Tile GetTile(Vector2 position, int layer) { TileLayer tileLayer = GetLayer(layer.ToString()) as TileLayer; if (tileLayer == null) { return(null); } position.X = (int)position.X; position.Y = (int)position.Y; Vector2 tilePosition = new Vector2((int)(position.X / TileWidth), (int)(position.Y / TileHeight)); if (tilePosition.X < 0 || tilePosition.Y < 0 || tilePosition.X > Width - 1 || tilePosition.Y > Height - 1) { return(null); } return(tileLayer.Tiles[(int)tilePosition.X, (int)tilePosition.Y]); }
/// <summary> /// Draws a single layer by layer name /// </summary> /// <param name="spriteBatch">The SpriteBatch to use to render the layer.</param> /// <param name="layerName">The name of the layer to draw.</param> /// <param name="gameCamera">The camera to use for positioning.</param> //public void DrawLayer(SpriteBatch spriteBatch, string layerName, Camera gameCamera) //{ // var l = GetLayer(layerName); // if (l == null) // return; // if (!l.Visible) // return; // TileLayer tileLayer = l as TileLayer; // if (tileLayer != null) // { // if (tileLayer.Properties.Contains("Shadows")) // DrawLayer(spriteBatch, tileLayer.Name, gameCamera, new Vector2(-10f, -10f), 0.2f); // DrawLayer(spriteBatch, l, gameCamera, new Vector2(0,0), tileLayer.Opacity, Color.White, false); // } //} /// <summary> /// Draws a single layer by layer name, with a specified color /// </summary> /// <param name="spriteBatch">The SpriteBatch to use to render the layer.</param> /// <param name="layerName">The name of the layer to draw.</param> /// <param name="gameCamera">The camera to use for positioning.</param> public void DrawLayer(SpriteBatch spriteBatch, string layerName, Camera gameCamera, Color color, bool silhouette, float scale) { var l = GetLayer(layerName); if (l == null) { return; } if (!l.Visible) { return; } TileLayer tileLayer = l as TileLayer; if (tileLayer != null) { DrawLayer(spriteBatch, l, gameCamera, color, silhouette, scale); } }
public Rectangle?CheckTileCollisionIntersect(Vector2 position, Rectangle rect, int layer) { TileLayer tileLayer = GetLayer(layer.ToString()) as TileLayer; if (tileLayer == null) { return(null); } position.X = (int)position.X; position.Y = (int)position.Y; Vector2 tilePosition = new Vector2((int)(position.X / TileWidth), (int)(position.Y / TileHeight)); if (tilePosition.X < 0 || tilePosition.Y < 0 || tilePosition.X > Width - 1 || tilePosition.Y > Height - 1) { return(null); } Tile collisionTile = tileLayer.Tiles[(int)tilePosition.X, (int)tilePosition.Y]; if (collisionTile == null) { return(null); } if (collisionTile.Properties.Contains("Portal")) { return(null); } return(Rectangle.Intersect(rect, new Rectangle((int)tilePosition.X * TileWidth, (int)tilePosition.Y * TileHeight, TileWidth, TileHeight))); return(null); }
private static bool TryMakeJetty(Map map, TileLayer terrainLayer, TileLayer waterLayer, Point start, Point direction) { Vector2 jettyPos = Helper.PtoV(start) * map.TileWidth; foreach (Jetty otherJ in map.Jetties) if ((otherJ.Position - jettyPos).Length() < 5000) return false; Rectangle bounds = new Rectangle(); Vector2 boatPos = Vector2.Zero; float boatRot = 0f; if (direction.Y == -1) { bounds = new Rectangle(start.X - 1, start.Y - 10, 2, 10); boatPos = (new Vector2(bounds.Left, bounds.Top) * map.TileWidth) + new Vector2(100, -100); } if (direction.Y == 1) { bounds = new Rectangle(start.X - 1, start.Y, 2, 10); boatPos = (new Vector2(bounds.Left, bounds.Bottom) * map.TileWidth) + new Vector2(100, 100); } if (direction.X == -1) { bounds = new Rectangle(start.X - 10, start.Y - 1, 10, 2); boatPos = (new Vector2(bounds.Left, bounds.Top) * map.TileWidth) + new Vector2(-100, 100); boatRot = MathHelper.PiOver2; } if (direction.X == 1) { bounds = new Rectangle(start.X, start.Y - 1, 10, 2); boatPos = (new Vector2(bounds.Right, bounds.Top) * map.TileWidth) + new Vector2(100, 100); boatRot = MathHelper.PiOver2; } for (int xx = bounds.Left; xx < bounds.Right; xx++) { for (int yy = bounds.Top; yy < bounds.Bottom; yy++) { terrainLayer.Tiles[xx, yy] = (direction.Y!=0?map.Tiles[JETTY_H]:map.Tiles[JETTY_V]); waterLayer.Tiles[xx, yy] = null; } } Jetty newJ = new Jetty(); newJ.Position = jettyPos; newJ.Bounds = bounds; newJ.BoatPosition = boatPos; newJ.BoatRotation = boatRot; map.Jetties.Add(newJ); return true; }
private static bool TryDrawBigTree(Map map, TileLayer wallLayer, int x, int y) { Rectangle thisTree = BIG_TREES[rand.Next(7)]; bool canFit = true; for (int xx = x; xx < x + thisTree.Width; xx++) for (int yy = y; yy < y + thisTree.Height; yy++) if (GetTileIndex(map, wallLayer, xx, yy) != TREE) canFit = false; if (canFit) { int mapx = x; int mapy = y; for (int xx = thisTree.Left; xx < thisTree.Right; xx++) { for (int yy = thisTree.Top; yy < thisTree.Bottom; yy++) { int tile = ((yy-1) * TILESHEET_WIDTH) + (xx % (TILESHEET_WIDTH+1)); wallLayer.Tiles[mapx, mapy] = map.Tiles[tile]; mapy++; } mapy = y; mapx++; } } return canFit; }
private static Vector2 TryFindSpawn(int x, int y, Map map, TileLayer layer, out bool foundspawn) { Vector2 returnPos = new Vector2(x * map.TileWidth, y * map.TileHeight) + (new Vector2(map.TileWidth, map.TileHeight)/2); if (GetTileIndex(map, layer, x, y) == SAND || GetTileIndex(map, layer, x, y) == SAND_ALT) { if(GetTileIndex(map, layer, x-5, y) == WATER || GetTileIndex(map, layer, x+5, y) == WATER || GetTileIndex(map, layer, x, y-5) == WATER || GetTileIndex(map, layer, x, y+5) == WATER) { foundspawn = true; } else foundspawn = false; } else foundspawn = false; return returnPos; }
static int GetTileIndex(Map map, TileLayer layer, int x, int y) { if (x > -1 && x < map.Width && y > -1 && y < map.Height && layer.Tiles[x, y]!=null) { return map.Tiles.IndexOf(layer.Tiles[x, y]); } return -1; }
private static void MakeBuildings(Map map, TileLayer wallLayer, TileLayer terrainLayer, TileLayer roofLayer, Compound newCompound) { Rectangle innerBounds = newCompound.InnerBounds; innerBounds.Inflate(-2, -2); // Helipad Building heliPad = null; for (int i = 0; i < 10; i++) { Point pos = new Point(innerBounds.Left + rand.Next(innerBounds.Width), innerBounds.Top + rand.Next(innerBounds.Height)); Rectangle rect = new Rectangle(pos.X - 3, pos.Y - 3, 6, 6); bool canPlace = true; foreach (Building b in newCompound.Buildings) { Rectangle br = b.Rect; br.Inflate(2, 2); if (br.Intersects(rect)) canPlace = false; } if (!innerBounds.Contains(rect)) canPlace = false; if (canPlace) { heliPad = new Building() { Rect = rect, Type = BuildingType.Helipad }; break; } } if (heliPad != null) { newCompound.Buildings.Add(heliPad); //for (int xx = heliPad.Rect.Left; xx < heliPad.Rect.Right; xx++) // for (int yy = heliPad.Rect.Top; yy < heliPad.Rect.Bottom; yy++) // terrainLayer.Tiles[xx, yy] = map.Tiles[CARPARK]; } // Buildings! for (int i = 0; i < 100; i++) { Building newBuilding = null; Point pos = new Point(innerBounds.Left + 4 + rand.Next(innerBounds.Width - 8), innerBounds.Top + 4 + rand.Next(innerBounds.Height-8)); Rectangle rect = new Rectangle(pos.X, pos.Y, 1, 1); rect.Inflate(5 + rand.Next(10), 5 + rand.Next(10)); bool canPlace = true; foreach (Building b in newCompound.Buildings) { Rectangle br = b.Rect; br.Inflate(2, 2); if (br.Intersects(rect)) canPlace = false; } if (!innerBounds.Contains(rect)) canPlace = false; if (canPlace) { newBuilding = new Building() { Rect = rect, Type = BuildingType.Building }; } if (newBuilding != null) { newCompound.Buildings.Add(newBuilding); // Outer walls wallLayer.Tiles[rect.Left, rect.Top] = map.Tiles[WALL_TL]; wallLayer.Tiles[rect.Right, rect.Top] = map.Tiles[WALL_TR]; wallLayer.Tiles[rect.Left, rect.Bottom] = map.Tiles[WALL_BL]; wallLayer.Tiles[rect.Right, rect.Bottom] = map.Tiles[WALL_BR]; roofLayer.Tiles[rect.Left, rect.Top] = map.Tiles[ROOF_TL]; roofLayer.Tiles[rect.Right, rect.Top] = map.Tiles[ROOF_TR]; roofLayer.Tiles[rect.Left, rect.Bottom] = map.Tiles[ROOF_BL]; roofLayer.Tiles[rect.Right, rect.Bottom] = map.Tiles[ROOF_BR]; for (int xx = rect.Left + 1; xx <= rect.Right - 1; xx++) { wallLayer.Tiles[xx, rect.Top] = map.Tiles[WALL_EDGE_UP]; wallLayer.Tiles[xx, rect.Bottom] = map.Tiles[WALL_EDGE_DOWN]; roofLayer.Tiles[xx, rect.Top] = map.Tiles[ROOF_EDGE_UP]; roofLayer.Tiles[xx, rect.Bottom] = map.Tiles[ROOF_EDGE_DOWN]; } for (int yy = rect.Top + 1; yy <= rect.Bottom - 1; yy++) { wallLayer.Tiles[rect.Left,yy] = map.Tiles[WALL_EDGE_LEFT]; wallLayer.Tiles[rect.Right,yy] = map.Tiles[WALL_EDGE_RIGHT]; roofLayer.Tiles[rect.Left, yy] = map.Tiles[ROOF_EDGE_LEFT]; roofLayer.Tiles[rect.Right, yy] = map.Tiles[ROOF_EDGE_RIGHT]; } for (int xx = rect.Left+1; xx <= rect.Right-1; xx++) { for (int yy = rect.Top+1; yy <= rect.Bottom-1; yy++) { roofLayer.Tiles[xx, yy] = map.Tiles[ROOF]; } } // Exits bool[] exits = new bool[4] { false, false, false, false }; exits[rand.Next(4)] = true; if (exits[0]) { int doorx = rand.Next(rect.Width - 7) + 3; for (int xx = rect.Left + doorx; xx < (rect.Left + doorx) + 4; xx++) { wallLayer.Tiles[xx, rect.Top] = null; roofLayer.Tiles[xx, rect.Top] = null; } } if (exits[1]) { int doorx = rand.Next(rect.Width - 7) + 3; for (int xx = rect.Left + doorx; xx < (rect.Left + doorx) + 4; xx++) { wallLayer.Tiles[xx, rect.Bottom] = null; roofLayer.Tiles[xx, rect.Bottom] = null; } } if (exits[2]) { int doory = rand.Next(rect.Height - 7) + 3; for (int yy = rect.Top + doory; yy < (rect.Top + doory) + 4; yy++) {wallLayer.Tiles[rect.Left, yy] = null; roofLayer.Tiles[rect.Left, yy] = null;} } if (exits[3]) { int doory = rand.Next(rect.Height - 7) + 3; for (int yy = rect.Top + doory; yy < (rect.Top + doory) + 4; yy++){ wallLayer.Tiles[rect.Right, yy] = null; roofLayer.Tiles[rect.Right, yy] = null;} } //for (int xx = newBuilding.Rect.Left; xx < newBuilding.Rect.Right; xx++) // for (int yy = newBuilding.Rect.Top; yy < newBuilding.Rect.Bottom; yy++) // terrainLayer.Tiles[xx, yy] = map.Tiles[WALL_HORIZ]; } } }
public void Initialize(Map map, Game game) { mapa = map; _solidos = mapa.GetLayer("Solidos") as TileLayer; _listaPlayers = new List<Player>(); _game = game; //Sonidos _impacto = _game.Content.Load<SoundEffect>("sound/SFX/Impacto"); }
private static void CreateCompounds(Map map, TileLayer terrainLayer, TileLayer wallLayer, TileLayer roofLayer, List<Compound> compounds, float[][] noise, float height, float distance, int minsize, LightingEngine lightingEngine, GraphicsDevice gd) { for (int y = 40; y < map.Width - 40; y++) { for (int x = 40; x < map.Height - 40; x++) { if (noise[y][x] > height) { Vector2 thisLoc = new Vector2(x * map.TileWidth, y * map.TileHeight); bool tooClose = false; foreach (Compound c in compounds) if ((c.Position - thisLoc).Length() < distance) tooClose = true; if (!tooClose) { Rectangle bounds = new Rectangle(x, y, 1, 1); bounds.Inflate(minsize, minsize); bounds.Inflate(rand.Next(5) * 2, rand.Next(5) * 2); bool tooBig = true; while (tooBig) { if (GetTileIndex(map, terrainLayer, bounds.Left, bounds.Top) != GRASS || GetTileIndex(map, terrainLayer, bounds.Right, bounds.Top) != GRASS || GetTileIndex(map, terrainLayer, bounds.Left, bounds.Bottom) != GRASS || GetTileIndex(map, terrainLayer, bounds.Right, bounds.Bottom) != GRASS) { tooBig = true; bounds.Inflate(-1, -1); } else tooBig = false; } if (bounds.Width >= minsize && bounds.Height >= minsize) { Compound newCompound = new Compound() { Position = thisLoc }; for (int xx = bounds.Left; xx <= bounds.Right; xx++) { for (int yy = bounds.Top; yy <= bounds.Bottom; yy++) { wallLayer.Tiles[xx, yy] = null; if (xx > bounds.Left + 2 && xx < bounds.Right - 2 && yy > bounds.Top + 2 && yy < bounds.Bottom - 2) terrainLayer.Tiles[xx, yy] = map.Tiles[MUD]; } } Rectangle innerBounds = bounds; innerBounds.Inflate(-3, -3); // Outer walls wallLayer.Tiles[innerBounds.Left, innerBounds.Top] = map.Tiles[WALL_TL]; wallLayer.Tiles[innerBounds.Right, innerBounds.Top] = map.Tiles[WALL_TR]; wallLayer.Tiles[innerBounds.Left, innerBounds.Bottom] = map.Tiles[WALL_BL]; wallLayer.Tiles[innerBounds.Right, innerBounds.Bottom] = map.Tiles[WALL_BR]; for (int xx = innerBounds.Left + 1; xx <= innerBounds.Right - 1; xx++) { wallLayer.Tiles[xx, innerBounds.Top] = map.Tiles[WALL_EDGE_UP]; wallLayer.Tiles[xx, innerBounds.Bottom] = map.Tiles[WALL_EDGE_DOWN]; } for (int yy = innerBounds.Top + 1; yy <= innerBounds.Bottom - 1; yy++) { wallLayer.Tiles[innerBounds.Left, yy] = map.Tiles[WALL_EDGE_LEFT]; wallLayer.Tiles[innerBounds.Right,yy] = map.Tiles[WALL_EDGE_RIGHT]; } newCompound.Bounds = bounds; newCompound.InnerBounds = innerBounds; // Exits bool[] exits = new bool[4] { false, false, false, false }; for(int i=0;i<4;i++) exits[rand.Next(4)] = true; bool carparkPlaced = false; Building carpark = null; if (exits[0]) { int doorx = rand.Next(innerBounds.Width - 7) + 3; for (int xx = innerBounds.Left + doorx; xx < (innerBounds.Left + doorx) + 4; xx++) wallLayer.Tiles[xx, innerBounds.Top] = null; if (!carparkPlaced && rand.Next(2) == 0) { carpark = new Building() { Type = BuildingType.Carpark, Rect = new Rectangle((innerBounds.Left + doorx), innerBounds.Top + 2, 4, 4) }; newCompound.Buildings.Add(carpark); carparkPlaced = true; } } if (exits[1]) { int doorx = rand.Next(innerBounds.Width - 7) + 3; for (int xx = innerBounds.Left + doorx; xx < (innerBounds.Left + doorx) + 4; xx++) wallLayer.Tiles[xx, innerBounds.Bottom] = null; if (!carparkPlaced && rand.Next(2) == 0) { carpark = new Building() { Type = BuildingType.Carpark, Rect = new Rectangle((innerBounds.Left + doorx), innerBounds.Bottom - 6, 4, 4) }; newCompound.Buildings.Add(carpark); carparkPlaced = true; } } if (exits[2]) { int doory = rand.Next(innerBounds.Height - 7) + 3; for (int yy = innerBounds.Top + doory; yy < (innerBounds.Top + doory) + 4; yy++) wallLayer.Tiles[innerBounds.Left,yy] = null; if (!carparkPlaced && rand.Next(2) == 0) { carpark = new Building() { Type = BuildingType.Carpark, Rect = new Rectangle(innerBounds.Left + 2, (innerBounds.Top + doory), 4, 4) }; newCompound.Buildings.Add(carpark); carparkPlaced = true; } } if (exits[3]) { int doory = rand.Next(innerBounds.Height - 7) + 3; for (int yy = innerBounds.Top + doory; yy < (innerBounds.Top + doory) + 4; yy++) wallLayer.Tiles[innerBounds.Right, yy] = null; if (!carparkPlaced && rand.Next(2) == 0) { carpark = new Building() { Type = BuildingType.Carpark, Rect = new Rectangle(innerBounds.Right - 6, (innerBounds.Top + doory), 4, 4) }; newCompound.Buildings.Add(carpark); carparkPlaced = true; } } int lightSpacing = 5; for (int xx = innerBounds.Left + 4; xx <= innerBounds.Right - 4; xx++) { lightSpacing++; if (lightSpacing == 6) { lightSpacing = 0; if (GetTileIndex(map, wallLayer, xx, innerBounds.Top) == WALL_EDGE_UP && GetTileIndex(map, wallLayer, xx - 2, innerBounds.Top) == WALL_EDGE_UP && GetTileIndex(map, wallLayer, xx + 2, innerBounds.Top) == WALL_EDGE_UP) { LightSource ls = new LightSource(gd, 300, LightAreaQuality.Low, Color.White, BeamStencilType.None, SpotStencilType.Half); ls.Rotation = MathHelper.PiOver2; ls.Position = new Vector2((xx * map.TileWidth) + (map.TileWidth / 2), ((innerBounds.Top + 1) * map.TileHeight)); lightingEngine.LightSources.Add(ls); } if (GetTileIndex(map, wallLayer, xx, innerBounds.Bottom) == WALL_EDGE_DOWN && GetTileIndex(map, wallLayer, xx - 2, innerBounds.Bottom) == WALL_EDGE_DOWN && GetTileIndex(map, wallLayer, xx + 2, innerBounds.Bottom) == WALL_EDGE_DOWN) { LightSource ls = new LightSource(gd, 300, LightAreaQuality.Low, Color.White, BeamStencilType.None, SpotStencilType.Half); ls.Rotation = MathHelper.PiOver2 + MathHelper.Pi; ls.Position = new Vector2((xx * map.TileWidth) + (map.TileWidth / 2), ((innerBounds.Bottom) * map.TileHeight)); lightingEngine.LightSources.Add(ls); } } } lightSpacing = 5; for (int yy = innerBounds.Top + 4; yy <= innerBounds.Bottom - 4; yy++) { lightSpacing++; if (lightSpacing == 6) { lightSpacing = 0; if (GetTileIndex(map, wallLayer, innerBounds.Left, yy) == WALL_EDGE_LEFT && GetTileIndex(map, wallLayer, innerBounds.Left, yy - 2) == WALL_EDGE_LEFT && GetTileIndex(map, wallLayer, innerBounds.Left, yy + 2) == WALL_EDGE_LEFT) { LightSource ls = new LightSource(gd, 300, LightAreaQuality.Low, Color.White, BeamStencilType.None, SpotStencilType.Half); //ls.Rotation = MathHelper.PiOver2; ls.Position = new Vector2(((innerBounds.Left+1) * map.TileWidth), (yy * map.TileHeight)+(map.TileHeight/2)); lightingEngine.LightSources.Add(ls); } if (GetTileIndex(map, wallLayer, innerBounds.Right, yy) == WALL_EDGE_RIGHT && GetTileIndex(map, wallLayer, innerBounds.Right, yy - 2) == WALL_EDGE_RIGHT && GetTileIndex(map, wallLayer, innerBounds.Right, yy + 2) == WALL_EDGE_RIGHT) { LightSource ls = new LightSource(gd, 300, LightAreaQuality.Low, Color.White, BeamStencilType.None, SpotStencilType.Half); ls.Rotation = MathHelper.Pi; ls.Position = new Vector2(((innerBounds.Right) * map.TileWidth), (yy * map.TileHeight) + (map.TileHeight / 2)); lightingEngine.LightSources.Add(ls); } } } //if (carpark!=null) // for (int xx = carpark.Rect.Left; xx < carpark.Rect.Right; xx++) // for (int yy = carpark.Rect.Top; yy < carpark.Rect.Bottom; yy++) // terrainLayer.Tiles[xx, yy] = map.Tiles[CARPARK]; MakeBuildings(map, wallLayer, terrainLayer, roofLayer, newCompound); compounds.Add(newCompound); } } } } } }
internal Map(ContentReader reader) { // read in the basic map information Version = new Version(reader.ReadString()); Orientation = (Orientation)reader.ReadByte(); WidthInTiles = reader.ReadInt32(); HeightInTiles = reader.ReadInt32(); TileWidth = reader.ReadInt32(); TileHeight = reader.ReadInt32(); Properties = new PropertyCollection(reader); bool makeTilesUnique = reader.ReadBoolean(); // create a list for our tiles List<Tile> tiles = new List<Tile>(); Tiles = new ReadOnlyCollection<Tile>(tiles); // read in each tile set int numTileSets = reader.ReadInt32(); for (int i = 0; i < numTileSets; i++) { // get the id and texture int firstId = reader.ReadInt32(); Texture2D texture = reader.ReadExternalReference<Texture2D>(); // read in each individual tile int numTiles = reader.ReadInt32(); for (int j = 0; j < numTiles; j++) { int id = firstId + j; Rectangle source = reader.ReadObject<Rectangle>(); PropertyCollection props = new PropertyCollection(reader); Tile t = new Tile(texture, source, props); while (id >= tiles.Count) { tiles.Add(null); } tiles.Insert(id, t); } } // read in all the layers List<Layer> layers = new List<Layer>(); Layers = new ReadOnlyCollection<Layer>(layers); int numLayers = reader.ReadInt32(); for (int i = 0; i < numLayers; i++) { Layer layer = null; // read generic layer data string type = reader.ReadString(); string name = reader.ReadString(); int width = reader.ReadInt32(); int height = reader.ReadInt32(); bool visible = reader.ReadBoolean(); float opacity = reader.ReadSingle(); PropertyCollection props = new PropertyCollection(reader); // calculate the default layer depth of the layer float layerDepth = 1f - (LayerDepthSpacing * i); // using the type, figure out which object to create if (type == "layer") { uint[] data = reader.ReadObject<uint[]>(); layer = new TileLayer(name, width, height, layerDepth, visible, opacity, props, this, data, makeTilesUnique); } else if (type == "objectgroup") { List<MapObject> objects = new List<MapObject>(); // read in all of our objects int numObjects = reader.ReadInt32(); for (int j = 0; j < numObjects; j++) { string objName = reader.ReadString(); string objType = reader.ReadString(); Rectangle objLoc = reader.ReadObject<Rectangle>(); PropertyCollection objProps = new PropertyCollection(reader); objects.Add(new MapObject(objName, objType, objLoc, objProps)); } layer = new MapObjectLayer(name, width, height, layerDepth, visible, opacity, props, objects); // read in the layer's color (layer as MapObjectLayer).Color = reader.ReadColor(); } else { throw new Exception("Invalid type: " + type); } layers.Add(layer); namedLayers.Add(name, layer); } }
/// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); font = Content.Load<SpriteFont>("font"); hudTex = Content.Load<Texture2D>("hud"); tilesSprite = new VoxelSprite(16, 16, 16); LoadVoxels.LoadSprite(Path.Combine(Content.RootDirectory, "tiles.vxs"), ref tilesSprite); gameMap = Content.Load<Map>("1"); tileLayer = (TileLayer)gameMap.GetLayer("tiles"); MapObjectLayer spawnLayer = (MapObjectLayer)gameMap.GetLayer("spawns"); gameWorld = new VoxelWorld(gameMap.Width, 11, 1); for(int yy=0;yy<11;yy++) for(int xx=0;xx<12;xx++) if(tileLayer.Tiles[xx,yy]!=null) gameWorld.CopySprite(xx*Chunk.X_SIZE, yy*Chunk.Y_SIZE, 0, tilesSprite.AnimChunks[tileLayer.Tiles[xx,yy].Index-1]); scrollColumn = 12; gameCamera = new Camera(GraphicsDevice, GraphicsDevice.Viewport); gameCamera.Position = new Vector3(0f, gameWorld.Y_SIZE * Voxel.HALF_SIZE, 0f); gameCamera.Target = gameCamera.Position; gameHero = new Hero(); gameHero.LoadContent(Content, GraphicsDevice); enemyController = new EnemyController(GraphicsDevice); enemyController.LoadContent(Content, spawnLayer); projectileController = new ProjectileController(GraphicsDevice); projectileController.LoadContent(Content); particleController = new ParticleController(GraphicsDevice); powerupController = new PowerupController(GraphicsDevice); powerupController.LoadContent(Content); gameStarfield = new Starfield(GraphicsDevice); drawEffect = new BasicEffect(GraphicsDevice) { World = gameCamera.worldMatrix, View = gameCamera.viewMatrix, Projection = gameCamera.projectionMatrix, VertexColorEnabled = true, }; }
internal Map(ContentReader reader) { // read in the basic map information Version = new Version(reader.ReadString()); Orientation = (Orientation)reader.ReadByte(); WidthInTiles = reader.ReadInt32(); HeightInTiles = reader.ReadInt32(); TileWidth = reader.ReadInt32(); TileHeight = reader.ReadInt32(); Properties = new PropertyCollection(reader); bool makeTilesUnique = reader.ReadBoolean(); // create a list for our tiles List <Tile> tiles = new List <Tile>(); Tiles = new ReadOnlyCollection <Tile>(tiles); // read in each tile set int numTileSets = reader.ReadInt32(); for (int i = 0; i < numTileSets; i++) { // get the id and texture int firstId = reader.ReadInt32(); Texture2D texture = reader.ReadExternalReference <Texture2D>(); // read in each individual tile int numTiles = reader.ReadInt32(); for (int j = 0; j < numTiles; j++) { int id = firstId + j; Rectangle source = reader.ReadObject <Rectangle>(); PropertyCollection props = new PropertyCollection(reader); Tile t = new Tile(texture, source, props); while (id >= tiles.Count) { tiles.Add(null); } tiles.Insert(id, t); } } // read in all the layers List <Layer> layers = new List <Layer>(); Layers = new ReadOnlyCollection <Layer>(layers); int numLayers = reader.ReadInt32(); for (int i = 0; i < numLayers; i++) { Layer layer = null; // read generic layer data string type = reader.ReadString(); string name = reader.ReadString(); int width = reader.ReadInt32(); int height = reader.ReadInt32(); bool visible = reader.ReadBoolean(); float opacity = reader.ReadSingle(); PropertyCollection props = new PropertyCollection(reader); // calculate the default layer depth of the layer float layerDepth = 1f - (LayerDepthSpacing * i); // using the type, figure out which object to create if (type == "layer") { uint[] data = reader.ReadObject <uint[]>(); layer = new TileLayer(name, width, height, layerDepth, visible, opacity, props, this, data, makeTilesUnique); } else if (type == "objectgroup") { List <MapObject> objects = new List <MapObject>(); // read in all of our objects int numObjects = reader.ReadInt32(); for (int j = 0; j < numObjects; j++) { string objName = reader.ReadString(); string objType = reader.ReadString(); Rectangle objLoc = reader.ReadObject <Rectangle>(); PropertyCollection objProps = new PropertyCollection(reader); objects.Add(new MapObject(objName, objType, objLoc, objProps)); } layer = new MapObjectLayer(name, width, height, layerDepth, visible, opacity, props, objects); // read in the layer's color (layer as MapObjectLayer).Color = reader.ReadColor(); } else { throw new Exception("Invalid type: " + type); } layers.Add(layer); namedLayers.Add(name, layer); } }
//private Layer collisionLayer; // Construct a TiledLib.Map from a TmxReader.map public Map(ContentManager content, string mapName) { string mapPath = AppDomain.CurrentDomain.BaseDirectory + "Content/" + mapName + ".tmx"; TmxMap tmx = new TmxMap(mapPath); Version = new Version(tmx.Version); switch(tmx.Orientation) { case TmxMap.OrientationType.Isometric: Orientation = Orientation.Isometric; break; case TmxMap.OrientationType.Orthogonal: Orientation = Orientation.Orthogonal; break; case TmxMap.OrientationType.Staggered: throw new Exception( "TiledLib doesn't support maps with Staggered " + "orientation."); } Width = tmx.Width; Height = tmx.Height; TileWidth = tmx.TileWidth; TileHeight = tmx.TileHeight; Properties = new PropertyCollection(); foreach(KeyValuePair<string, string> kvp in tmx.Properties) { Properties.Add(kvp); } // Create a list for our tiles List<Tile> tiles = new List<Tile>(); Tiles = new Collection<Tile>(tiles); // Read in each TileSet foreach (TmxTileset ts in tmx.Tilesets) { string tilesetName = ts.Name; Texture2D texture = content.Load<Texture2D>(ts.Image.Source); bool collisionSet = ts.Properties.ContainsKey("CollisionSet") && ts.Properties["CollisionSet"] == "True" ? true : false; /* TODO: Add this intelligence to TiledSharp. * If the texture is bigger than a individual tile, infer all the * additional tiles that must be created. */ if (texture.Width > ts.TileWidth || texture.Height > ts.TileHeight) { // Deconstruct tileset to individual tiles int id = 0; for (int y = 0; y < texture.Height / ts.TileHeight; y++) { for (int x = 0; x < texture.Width / ts.TileWidth; x++) { Rectangle source = new Rectangle( x * ts.TileWidth, y * ts.TileHeight, ts.TileWidth, ts.TileHeight ); Color[] collisionData = null; bool[] collisionBitData = null; PropertyCollection props = new PropertyCollection(); TmxTilesetTile tsTile = ts.Tiles.Find(i => i.Id == id); if(tsTile != null) { foreach (KeyValuePair<string, string> kvp in tsTile.Properties) { props.Add(kvp); // Inherit tilesets collision bool collidable = collisionSet; if (kvp.Key == "CollisionSet") { // Allow override per tile if (kvp.Value == "True") { collidable = true; } else { collidable = false; } } if (collidable) { int numOfBytes = ts.TileWidth * ts.TileHeight; collisionData = new Color[numOfBytes]; collisionBitData = new bool[numOfBytes]; texture.GetData<Color>( 0, source, collisionData, 0, numOfBytes ); for (int col = 0; col < numOfBytes; col++) { if (collisionData[col].A > 0) { collisionBitData[col] = true; } } collisionData = null; } } } Tile t = new Tile( texture, source, props, collisionBitData ); while (id >= tiles.Count) { tiles.Add(null); } tiles.Insert(id + ts.FirstGid, t); id++; } } } } // Process Map Items (layers, objectgroups, etc.) List<Layer> layers = new List<Layer>(); Layers = new Collection<Layer>(layers); foreach(TmxLayer l in tmx.Layers) { Layer layer = null; PropertyCollection props = new PropertyCollection(); foreach(KeyValuePair<string, string> kvp in l.Properties) { props.Add(kvp); } layer = new TileLayer( l.Name, tmx.Width, // As of TiledQT always same as layer. tmx.Height, // As of TiledQT always same as layer. l.Visible, (float) l.Opacity, props, this, l.Tiles ); layers.Add(layer); namedLayers.Add(l.Name, layer); } foreach(TmxObjectGroup og in tmx.ObjectGroups) { Layer layer = null; PropertyCollection props = new PropertyCollection(); foreach(KeyValuePair<string, string> kvp in og.Properties) { props.Add(kvp); } List<MapObject> objects = new List<MapObject>(); // read in all of our objects foreach(TmxObjectGroup.TmxObject i in og.Objects) { Rectangle objLoc = new Rectangle( i.X, i.Y, i.Width, i.Height ); List<Point> objPoints = new List<Point>(); if (i.Points != null) { foreach (Tuple<int, int> tuple in i.Points) { objPoints.Add(new Point(tuple.Item1, tuple.Item2)); } } PropertyCollection objProps = new PropertyCollection(); foreach(KeyValuePair<string, string> kvp in i.Properties) { objProps.Add(kvp); } objects.Add( new MapObject( i.Name, i.Type, objLoc, objPoints, objProps) ); } layer = new MapObjectLayer( og.Name, tmx.Width, tmx.Height, og.Visible, (float) og.Opacity, props, objects ); layers.Add(layer); namedLayers.Add(og.Name, layer); } }
internal Map(ContentReader reader) { // read in the basic map information Version = new Version(reader.ReadString()); Orientation = (Orientation)reader.ReadByte(); Width = reader.ReadInt32(); Height = reader.ReadInt32(); TileWidth = reader.ReadInt32(); TileHeight = reader.ReadInt32(); Properties = new PropertyCollection(); Properties.Read(reader); // create a list for our tiles List<Tile> tiles = new List<Tile>(); Tiles = new Collection<Tile>(tiles); // read in each tile set int numTileSets = reader.ReadInt32(); for (int i = 0; i < numTileSets; i++) { // get the id and texture int firstId = reader.ReadInt32(); string tilesetName = reader.ReadString(); bool collisionSet = reader.ReadBoolean(); Texture2D texture = reader.ReadExternalReference<Texture2D>(); // read in each individual tile int numTiles = reader.ReadInt32(); for (int j = 0; j < numTiles; j++) { int id = firstId + j; // Read the source rectangle from the file. Rectangle source = reader.ReadObject<Rectangle>(); PropertyCollection props = new PropertyCollection(); props.Read(reader); // Read in color data for collision purposes // You'll probably want to limit this to just the tilesets that are used for collision // I'm checking for the name of my tileset that contains wall tiles // Color data takes up a fair bit of RAM Color[] collisionData = null; bool[] collisionBitData = null; if (collisionSet) { int numOfBytes = TileWidth * TileHeight; collisionData = new Color[numOfBytes]; collisionBitData = new bool[numOfBytes]; texture.GetData<Color>( 0, source, collisionData, 0, numOfBytes ); for (int col = 0; col < numOfBytes; col++) { if (collisionData[col].A > 0) { collisionBitData[col] = true; } } collisionData = null; } Tile t = new Tile(texture, source, props, collisionBitData); while (id >= tiles.Count) { tiles.Add(null); } tiles.Insert(id, t); } } // read in all the layers List<Layer> layers = new List<Layer>(); Layers = new Collection<Layer>(layers); int numLayers = reader.ReadInt32(); for (int i = 0; i < numLayers; i++) { Layer layer = null; // read generic layer data string type = reader.ReadString(); string name = reader.ReadString(); int width = reader.ReadInt32(); int height = reader.ReadInt32(); bool visible = reader.ReadBoolean(); float opacity = reader.ReadSingle(); PropertyCollection props = new PropertyCollection(); props.Read(reader); // using the type, figure out which object to create if (type == "layer") { int[] data = reader.ReadObject<int[]>(); layer = new TileLayer(name, width, height, visible, opacity, props, this, data); } else if (type == "objectgroup") { List<MapObject> objects = new List<MapObject>(); // read in all of our objects int numObjects = reader.ReadInt32(); for (int j = 0; j < numObjects; j++) { string objName = reader.ReadString(); string objType = reader.ReadString(); Rectangle objLoc = reader.ReadObject<Rectangle>(); List<Point> objPoints = reader.ReadObject<List<Point>>(); PropertyCollection objProps = new PropertyCollection(); objProps.Read(reader); objects.Add(new MapObject(objName, objType, objLoc, objPoints, objProps)); } layer = new MapObjectLayer(name, width, height, visible, opacity, props, objects); } else { throw new Exception("Invalid type: " + type); } layers.Add(layer); namedLayers.Add(name, layer); } }
static int CountSurroundingTiles(Map map, TileLayer layer, int x, int y) { int count = 0; for (int yy = y - 1; yy <= y + 1; yy++) for (int xx = x - 1; xx <= x + 1; xx++) if(xx>=0 && xx<map.Width&&yy>=0 && yy<map.Height) if (layer.Tiles[xx, yy] != null && !(x == xx && y == yy)) count++; return count; }
//private Layer collisionLayer; // Construct a TiledLib.Map from a TmxReader.map public Map(ContentManager content, string mapName) { string mapPath = AppDomain.CurrentDomain.BaseDirectory + "Content/" + mapName + ".tmx"; TmxMap tmx = new TmxMap(mapPath); Version = new Version(tmx.Version); switch (tmx.Orientation) { case TmxMap.OrientationType.Isometric: Orientation = Orientation.Isometric; break; case TmxMap.OrientationType.Orthogonal: Orientation = Orientation.Orthogonal; break; case TmxMap.OrientationType.Staggered: throw new Exception( "TiledLib doesn't support maps with Staggered " + "orientation."); } Width = tmx.Width; Height = tmx.Height; TileWidth = tmx.TileWidth; TileHeight = tmx.TileHeight; Properties = new PropertyCollection(); foreach (KeyValuePair <string, string> kvp in tmx.Properties) { Properties.Add(kvp); } // Create a list for our tiles List <Tile> tiles = new List <Tile>(); Tiles = new Collection <Tile>(tiles); // Read in each TileSet foreach (TmxTileset ts in tmx.Tilesets) { string tilesetName = ts.Name; Texture2D texture = content.Load <Texture2D>(ts.Image.Source); bool collisionSet = ts.Properties.ContainsKey("CollisionSet") && ts.Properties["CollisionSet"] == "True" ? true : false; /* TODO: Add this intelligence to TiledSharp. * If the texture is bigger than a individual tile, infer all the * additional tiles that must be created. */ if (texture.Width > ts.TileWidth || texture.Height > ts.TileHeight) { // Deconstruct tileset to individual tiles int id = 0; for (int y = 0; y < texture.Height / ts.TileHeight; y++) { for (int x = 0; x < texture.Width / ts.TileWidth; x++) { Rectangle source = new Rectangle( x * ts.TileWidth, y * ts.TileHeight, ts.TileWidth, ts.TileHeight ); Color[] collisionData = null; bool[] collisionBitData = null; PropertyCollection props = new PropertyCollection(); TmxTilesetTile tsTile = ts.Tiles.Find(i => i.Id == id); if (tsTile != null) { foreach (KeyValuePair <string, string> kvp in tsTile.Properties) { props.Add(kvp); // Inherit tilesets collision bool collidable = collisionSet; if (kvp.Key == "CollisionSet") { // Allow override per tile if (kvp.Value == "True") { collidable = true; } else { collidable = false; } } if (collidable) { int numOfBytes = ts.TileWidth * ts.TileHeight; collisionData = new Color[numOfBytes]; collisionBitData = new bool[numOfBytes]; texture.GetData <Color>( 0, source, collisionData, 0, numOfBytes ); for (int col = 0; col < numOfBytes; col++) { if (collisionData[col].A > 0) { collisionBitData[col] = true; } } collisionData = null; } } } Tile t = new Tile( texture, source, props, collisionBitData ); while (id >= tiles.Count) { tiles.Add(null); } tiles.Insert(id + ts.FirstGid, t); id++; } } } } // Process Map Items (layers, objectgroups, etc.) List <Layer> layers = new List <Layer>(); Layers = new Collection <Layer>(layers); foreach (TmxLayer l in tmx.Layers) { Layer layer = null; PropertyCollection props = new PropertyCollection(); foreach (KeyValuePair <string, string> kvp in l.Properties) { props.Add(kvp); } layer = new TileLayer( l.Name, tmx.Width, // As of TiledQT always same as layer. tmx.Height, // As of TiledQT always same as layer. l.Visible, (float)l.Opacity, props, this, l.Tiles ); layers.Add(layer); namedLayers.Add(l.Name, layer); } foreach (TmxObjectGroup og in tmx.ObjectGroups) { Layer layer = null; PropertyCollection props = new PropertyCollection(); foreach (KeyValuePair <string, string> kvp in og.Properties) { props.Add(kvp); } List <MapObject> objects = new List <MapObject>(); // read in all of our objects foreach (TmxObjectGroup.TmxObject i in og.Objects) { Rectangle objLoc = new Rectangle( i.X, i.Y, i.Width, i.Height ); List <Point> objPoints = new List <Point>(); if (i.Points != null) { foreach (Tuple <int, int> tuple in i.Points) { objPoints.Add(new Point(tuple.Item1, tuple.Item2)); } } PropertyCollection objProps = new PropertyCollection(); foreach (KeyValuePair <string, string> kvp in i.Properties) { objProps.Add(kvp); } objects.Add( new MapObject( i.Name, i.Type, objLoc, objPoints, objProps) ); } layer = new MapObjectLayer( og.Name, tmx.Width, tmx.Height, og.Visible, (float)og.Opacity, props, objects ); layers.Add(layer); namedLayers.Add(og.Name, layer); } }
protected override void LoadScreenContent(ContentManager content) { background = new Background(content, "Images/GameplayBackground"); map = new Map[7]; map[0] = content.Load<Map>("Maps/map01"); map[1] = content.Load<Map>("Maps/map02"); map[2] = content.Load<Map>("Maps/map03"); map[3] = content.Load<Map>("Maps/map04"); map[4] = content.Load<Map>("Maps/map05"); map[5] = content.Load<Map>("Maps/map06"); map[6] = content.Load<Map>("Maps/map07"); player = new Player(content); player.TilePosition = new Vector2(1, 17); hud = new HUD(content, player); mapNumber = 0; leftButton = new Button(content, "", new Vector2(800, 650), Color.White, Color.White, "Images/LeftButton"); rightButton = new Button(content, "", new Vector2(900, 650), Color.White, Color.White, "Images/RightButton"); upButton = new Button(content, "", new Vector2(850, 595), Color.White, Color.White, "Images/UpButton"); downButton = new Button(content, "", new Vector2(850, 705), Color.White, Color.White, "Images/DownButton"); copyTileLayer = map[mapNumber].GetLayer("Layer") as TileLayer; tileLayer = copyTileLayer; blankTile = tileLayer.Tiles[19, 0]; walkableTile = tileLayer.Tiles[19, 1]; enemyTile = tileLayer.Tiles[19, 2]; exitTile = tileLayer.Tiles[19, 3]; enemykilledTile = tileLayer.Tiles[19, 4]; for (int y = 0; y < tileLayer.Height; y++) { for (int x = 0; x < 19; x++) { if (tileLayer.Tiles[x, y] == enemykilledTile) { tileLayer.Tiles[x, y] = enemyTile; } } } attackButton = new Button(content, "Attack", new Vector2(ScreenWidth / 2 + 220, 250), Color.Blue, Color.White); magicButton = new Button(content, "Magic", new Vector2(ScreenWidth / 2 + 220, 325), Color.Blue, Color.White); potionButton = new Button(content, "Potion", new Vector2(ScreenWidth / 2 + 220, 400), Color.Blue, Color.White); minion = new Minion(content); boss = new Boss(content); inBattle = false; bossBattle = false; #region Pregame playerCreated = false; keydown = (char)0; enterplayernameText = new Text(content.Load<SpriteFont>("Fonts/buttonFont"), "Enter Characters Name:", new Vector2(350, 200)); confirmnameButton = new Button(content, "Enter", new Vector2(425, 550), Color.Blue, Color.White); textenterbox = content.Load<Texture2D>("Images/TextInputBar"); playername = new Text(content.Load<SpriteFont>("Fonts/buttonFont"),"", new Vector2(375, 400), Color.Blue); charAmt = 0; nameComplete = false; enteredName = new char[8]; for (int i = 0; i < enteredName.Length; i++) { enteredName[i] = ' '; } chooseclasstext = new Text(content.Load<SpriteFont>("Fonts/buttonFont"), "Choose Characters Class:", new Vector2(340, 200)); paladinButton = new Button(content, "Paladin", new Vector2(425, 400), Color.Blue, Color.White); casterButton = new Button(content, "Caster", new Vector2(425, 500), Color.Blue, Color.White); rogueButton = new Button(content, "Rogue", new Vector2(425, 600), Color.Blue, Color.White); storyContinueButton = new Button(content, "Continue", new Vector2(800, 700), Color.Blue, Color.White); classComplete = false; storytexts = new Texture2D[3]; storyCount = 0; storytexts[0] = content.Load<Texture2D>("Images/Storytext1"); storytexts[1] = content.Load<Texture2D>("Images/Storytext2"); storytexts[2] = content.Load<Texture2D>("Images/Storytext3"); #endregion }
public void Update(Map map) { mapa = map; _solidos = mapa.GetLayer("Solidos") as TileLayer; }
//private Layer collisionLayer; internal Map(ContentReader reader) { // read in the basic map information Version = new Version(reader.ReadString()); Orientation = (Orientation)reader.ReadByte(); Width = reader.ReadInt32(); Height = reader.ReadInt32(); TileWidth = reader.ReadInt32(); TileHeight = reader.ReadInt32(); Properties = new PropertyCollection(); Properties.Read(reader); // create a list for our tiles List <Tile> tiles = new List <Tile>(); Tiles = new Collection <Tile>(tiles); // read in each tile set int numTileSets = reader.ReadInt32(); for (int i = 0; i < numTileSets; i++) { // get the id and texture int firstId = reader.ReadInt32(); string tilesetName = reader.ReadString(); bool collisionSet = reader.ReadBoolean(); Texture2D texture = reader.ReadExternalReference <Texture2D>(); Texture2D whiteTexture = reader.ReadExternalReference <Texture2D>(); // Read in color data for collision purposes // You'll probably want to limit this to just the tilesets that are used for collision // I'm checking for the name of my tileset that contains wall tiles // Color data takes up a fair bit of RAM Color[] collisionData = null; bool[] collisionBitData = null; if (collisionSet) { collisionData = new Color[texture.Width * texture.Height]; collisionBitData = new bool[texture.Width * texture.Height]; texture.GetData <Color>(collisionData); for (int col = 0; col < collisionData.Length; col++) { if (collisionData[col].A > 0) { collisionBitData[col] = true; } } collisionData = null; } // read in each individual tile int numTiles = reader.ReadInt32(); for (int j = 0; j < numTiles; j++) { int id = firstId + j; Rectangle source = reader.ReadObject <Rectangle>(); PropertyCollection props = new PropertyCollection(); props.Read(reader); Tile t = new Tile(texture, whiteTexture, source, props, collisionBitData); while (id >= tiles.Count) { tiles.Add(null); } tiles.Insert(id, t); } } // read in all the layers List <Layer> layers = new List <Layer>(); Layers = new ReadOnlyCollection <Layer>(layers); int numLayers = reader.ReadInt32(); for (int i = 0; i < numLayers; i++) { Layer layer = null; // read generic layer data string type = reader.ReadString(); string name = reader.ReadString(); int width = reader.ReadInt32(); int height = reader.ReadInt32(); bool visible = reader.ReadBoolean(); float opacity = reader.ReadSingle(); PropertyCollection props = new PropertyCollection(); props.Read(reader); // using the type, figure out which object to create if (type == "layer") { int[] data = reader.ReadObject <int[]>(); layer = new TileLayer(name, width, height, visible, opacity, props, this, data); } else if (type == "objectgroup") { List <MapObject> objects = new List <MapObject>(); // read in all of our objects int numObjects = reader.ReadInt32(); for (int j = 0; j < numObjects; j++) { string objName = reader.ReadString(); string objType = reader.ReadString(); Rectangle objLoc = reader.ReadObject <Rectangle>(); List <Point> objPoints = reader.ReadObject <List <Point> >(); PropertyCollection objProps = new PropertyCollection(); objProps.Read(reader); objects.Add(new MapObject(objName, objType, objLoc, objPoints, objProps)); } layer = new MapObjectLayer(name, width, height, visible, opacity, props, objects); } else { throw new Exception("Invalid type: " + type); } layers.Add(layer); namedLayers.Add(name, layer); } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jo = JObject.Load(reader); byte[] buffer = null; BaseLayer result; switch (jo["type"].Value <string>()) { case "tilelayer": result = new TileLayer(); if (jo["encoding"]?.Value <string>() == "base64") { buffer = Convert.FromBase64String(jo["data"].Value <string>()); jo["data"].Replace(JToken.FromObject(new int[0])); } break; case "objectgroup": result = new ObjectLayer(); break; case "imagelayer": result = new ImageLayer(); break; default: return(null); } serializer.Populate(jo.CreateReader(), result); if (result is TileLayer tl && buffer != null) { switch (tl.Compression) { case null: tl.Data = new int[buffer.Length / sizeof(int)]; Buffer.BlockCopy(buffer, 0, tl.Data, 0, buffer.Length); break; case "zlib": using (var mStream = new MemoryStream(buffer)) { using (var stream = new Zlib.ZlibStream(mStream, Zlib.CompressionMode.Decompress)) { var bufferSize = result.Width * result.Height * sizeof(int); Array.Resize(ref buffer, bufferSize); stream.Read(buffer, 0, bufferSize); if (stream.ReadByte() != -1) { throw new JsonException(); } tl.Data = new int[result.Width * result.Height]; Buffer.BlockCopy(buffer, 0, tl.Data, 0, buffer.Length); } } break; case "gzip": using (var mStream = new MemoryStream(buffer)) { using (var stream = new Zlib.GZipStream(mStream, Zlib.CompressionMode.Decompress)) { var bufferSize = result.Width * result.Height * sizeof(int); Array.Resize(ref buffer, bufferSize); stream.Read(buffer, 0, bufferSize); if (stream.ReadByte() != -1) { throw new JsonException(); } tl.Data = new int[result.Width * result.Height]; Buffer.BlockCopy(buffer, 0, tl.Data, 0, buffer.Length); } } break; default: throw new NotImplementedException($"Compression: {tl.Compression}"); } } return(result); }
protected override void UpdateScreen(GameTime gameTime, DisplayOrientation displayOrientation) { if (player.CurrentHP < 1) { changeScreenDelegate(ScreenState.GameOver); this.LoadScreenContent(content); } if (playerCreated && !inBattle) { GameplayTurnCheck(); } else if (inBattle) { if (!bossBattle) { hud.Update(player); minion.Update(gameTime); if (input.CheckMouseRelease(attackButton) && input.PreviousMouseState.LeftButton == ButtonState.Pressed && player.TurnBattle && !minion.dead) { minion.HP -= random.Next(0, player.DAM); player.TurnBattle = false; } if (input.CheckMouseRelease(magicButton) && input.PreviousMouseState.LeftButton == ButtonState.Pressed && player.TurnBattle && !minion.dead && player.CurrentMP >= player.MAGCOS) { minion.HP -= random.Next(0, player.MAGDAM); player.CurrentMP -= player.MAGCOS; player.TurnBattle = false; } if (input.CheckMouseRelease(potionButton) && input.PreviousMouseState.LeftButton == ButtonState.Pressed && player.TurnBattle && !minion.dead && player.Potions > 0) { player.CurrentHP = player.MaxHP; player.TurnBattle = false; player.Potions--; } if (!player.TurnBattle) { player.CurrentHP -= random.Next(0, minion.DAM); player.TurnBattle = true; } if (minion.HP <= 0) { minion.dead = true; player.CurrentXP += minion.XP; inBattle = false; minion.Reset(); } } else { hud.Update(player); boss.Update(gameTime); if (input.CheckMouseRelease(attackButton) && input.PreviousMouseState.LeftButton == ButtonState.Pressed && player.TurnBattle && !boss.dead) { boss.HP -= random.Next(0, player.DAM); player.TurnBattle = false; } if (input.CheckMouseRelease(magicButton) && input.PreviousMouseState.LeftButton == ButtonState.Pressed && player.TurnBattle && !boss.dead && player.CurrentMP >= player.MAGCOS) { boss.HP -= random.Next(0, player.MAGDAM); player.CurrentMP -= player.MAGCOS; player.TurnBattle = false; } if (input.CheckMouseRelease(potionButton) && input.PreviousMouseState.LeftButton == ButtonState.Pressed && player.TurnBattle && !boss.dead && player.Potions > 0) { player.CurrentHP = player.MaxHP; player.TurnBattle = false; player.Potions--; } if (!player.TurnBattle) { player.CurrentHP -= random.Next(0, boss.DAM); player.TurnBattle = true; } if (boss.HP <= 0) { if (mapNumber < 6) { player.Potions += 2; boss.dead = true; player.Pieces++; player.CurrentXP += boss.XP; inBattle = false; boss.Reset(); player.TilePosition = new Vector2(1, 17); mapNumber++; tileLayer = null; copyTileLayer = map[mapNumber].GetLayer("Layer") as TileLayer; tileLayer = copyTileLayer; blankTile = tileLayer.Tiles[19, 0]; walkableTile = tileLayer.Tiles[19, 1]; enemyTile = tileLayer.Tiles[19, 2]; exitTile = tileLayer.Tiles[19, 3]; enemykilledTile = tileLayer.Tiles[19, 4]; bossBattle = false; for (int y = 0; y < tileLayer.Height; y++) { for (int x = 0; x < 19; x++) { if (tileLayer.Tiles[x, y] == enemykilledTile) { tileLayer.Tiles[x, y] = enemyTile; } } } } else { changeScreenDelegate(ScreenState.GameWin); LoadScreenContent(content); } } } } else { if (!nameComplete) { currentState = Keyboard.GetState(); if (currentState.IsKeyDown(Keys.Back)) { keydown = '.'; } if (currentState.IsKeyUp(Keys.Back) && keydown == '.' && charAmt >= 0) { keydown = (char)0; enteredName[charAmt] = ' '; if (charAmt != 0) charAmt--; } char tempc = GetCharFromKeyboard(currentState); if (charAmt < 8 && tempc != (char)0) { enteredName[charAmt] = tempc; charAmt++; } enteredName[0] = char.ToUpper(enteredName[0]); playername.ChangeText(new string(enteredName)); if (input.CheckMouseRelease(confirmnameButton) && input.PreviousMouseState.LeftButton == ButtonState.Pressed) { nameComplete = true; } } else if (!classComplete) { if (input.CheckMouseRelease(paladinButton) && input.PreviousMouseState.LeftButton == ButtonState.Pressed) { player.CreatePlayer(0, new string(enteredName).ToString()); classComplete = true; } if (input.CheckMouseRelease(casterButton) && input.PreviousMouseState.LeftButton == ButtonState.Pressed) { player.CreatePlayer(1, new string(enteredName).ToString()); classComplete = true; } if (input.CheckMouseRelease(rogueButton) && input.PreviousMouseState.LeftButton == ButtonState.Pressed) { player.CreatePlayer(2, new string(enteredName).ToString()); classComplete = true; } } else { if (input.CheckMouseRelease(storyContinueButton) && input.PreviousMouseState.LeftButton == ButtonState.Pressed) { if (storyCount < 2) { storyCount++; } else { playerCreated = true; } } } } }
static int CountSurroundingTiles(Map map, TileLayer layer, int x, int y, int index) { int count = 0; for (int yy = y - 1; yy <= y + 1; yy++) for (int xx = x - 1; xx <= x + 1; xx++) if (GetTileIndex(map, layer, xx, yy) == index && !(x == xx && y == yy)) count++; return count; }