public override void Activate(object obj) { if (obj != null) { level = Level.LoadFromFile(obj as string); foreach (var res in level.RequiredResources) { requiredResources.Add(res); } requiredResources.Add(ResMan.NewTexture2D("bug")); requiredResources.Add(ResMan.NewTexture2D("bullet")); } if (!HandleResources()) return; }
public static Level LoadFromFile(string filename) { Level lvl = new Level(); var res_list = new List<string>(); XDocument doc = XDocument.Load(filename); var raw = (from x in doc.Descendants() select x.Value).First(); res_list = (from x in doc.Root.Attributes("backgrounds") select x.Value).First().Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList(); var additional_resources = (from x in doc.Root.Attributes("images") select x.Value).First().Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList(); lvl.textureMap = res_list; foreach (var item in res_list) { lvl.RequiredResources.Add(ResMan.NewTexture2D(item)); } foreach (var item in additional_resources) { lvl.RequiredResources.Add(ResMan.NewTexture2D(item)); } string[] lines = raw.Split('\n'); lvl.rows = lines.Length; lvl.cols = lines[0].Split(',').Length; lvl.tileMap = new int[lvl.rows, lvl.cols]; for (int y = 0; y < lvl.rows; y++) { string[] entries = lines[y].Split(','); for (int x = 0; x < lvl.cols; x++) { lvl.tileMap[y, x] = int.Parse(entries[x]); } } var obstacles = from x in doc.Descendants("Obstacles").Descendants("tile") select new { tileIndex = int.Parse(x.Attribute("tx").Value.ToString()) + 1, Position = new Vector2( int.Parse(x.Attribute("x").Value.ToString()) * 256 + 128, int.Parse(x.Attribute("y").Value.ToString()) * 256 + 128) }; foreach (var obstacle in obstacles) { if(lvl.mapObstacles.Keys.Contains(obstacle.tileIndex)) { lvl.mapObstacles[obstacle.tileIndex].Add(obstacle.Position); } else { lvl.mapObstacles[obstacle.tileIndex] = new List<Vector2>(); lvl.mapObstacles[obstacle.tileIndex].Add(obstacle.Position); } } foreach (var key in lvl.mapObstacles.Keys) { lvl.RequiredResources.Add(ResMan.NewTexture2D("obstacle_" + key.ToString())); } var stones = from x in doc.Root.Descendants("Entities").Descendants("Stone") select new Vector2(float.Parse(x.Attribute("x").Value), float.Parse(x.Attribute("y").Value)); lvl.dirtyObstacles["Stone"] = stones.ToList(); var fires = from x in doc.Root.Descendants("Entities").Descendants("Fire") select new Vector2(float.Parse(x.Attribute("x").Value), float.Parse(x.Attribute("y").Value)); lvl.dirtyObstacles["Fire"] = fires.ToList(); lvl.Filename = filename; return lvl; }