Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Example based on http://msdn.microsoft.com/en-us/library/db5x7c0d.aspx
- Consider we have a level in this format, 5x5 tiles:
- 0,1,0,0,0
- 0,1,0,0,0
- 0,1,0,0,0
- 0,1,1,1,1
- 0,0,0,0,0
- */
- using System;
- using System.IO;
- using Microsoft.Xna.Framework
- using Microsoft.Xna.Framework.Graphics
- class Tile
- {
- public Vector2 Position { get; private set; }
- public Texture2D Texture { get; private set; }
- public Tile(Vector2 vec, Texture2D tex)
- {
- position = vec;
- texture = tex;
- }
- }
- class Level
- {
- //These will be explained as they are used
- int xCounter, yCounter, levelWidth, levelHeight;
- //This holds all our tiles to be drawn later
- List<Tile> Tiles;
- public void Level()
- {
- xCounter = 0;
- yCounter = 0;
- levelWidth = 64;
- levelHeight = 64;
- Tiles = new List<Vector2>();
- }
- public void LoadLevel(ContentManager Content)
- {
- try
- {
- // Create an instance of StreamReader to read from a file.
- // The using statement also closes the StreamReader.
- using (StreamReader sr = new StreamReader("Level01.txt"))
- {
- String line;
- // Read and display lines from the file until the end of
- // the file is reached.
- while ((line = sr.ReadLine()) != null)
- {
- string[] tempTiles = line.Split(','); //Split the line into individual tiles seperated by commas
- //Now we loop through each string in the array to get the first row of tiles
- foreach(string s in tempTiles)
- {
- //if we multiple the x value by the width then we get the current tiles x position in world, same with y.
- //The Tile class also takes a Texture for drawing
- //if the current string reads as 0 then we expect a grass tile
- if(s == 0)
- {
- Tiles.Add(new Tile(new Vector2(x * levelWidth, y * levelHeight), Content.Load<Texture2D>("grass")));
- }
- //if the current string reads as 1 then we expect a dirt tile
- if(s == 1)
- {
- Tiles.Add(new Tile(new Vector2(x * levelWidth, y * levelHeight), Content.Load<Texture2D>("dirt")));
- }
- xCounter++; //Increment x so we can get the correct world position
- }
- }
- xCounter = 0; //Reset x as we are moving to the next line
- yCounter++; //Incremement y to get the correct world position
- }
- xCounter = 0; //Reset what we've used here, just in case.
- yCounter = 0; //Reset what we've used here, just in case.
- }
- catch (Exception e)
- {
- // Let the user know what went wrong.
- Console.WriteLine("The file could not be read:");
- Console.WriteLine(e.Message);
- }
- }
- public void Draw(SpriteBatch spriteBatch)
- {
- spriteBatch.Begin();
- foreach(Tile t in Tiles)
- {
- spriteBatch.Draw(t.Texture, t.Position, Color.White);
- }
- spriteBatch.End();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment