2 using System.Collections.Generic;
6 using System.Runtime.Serialization;
7 using System.Diagnostics;
8 using Microsoft.Xna.Framework;
9 using Microsoft.Xna.Framework.Graphics;
10 using System.Reflection;
15 /// A map object represents the map or virtual world where players and other
16 /// game entities exist. The map consists of a grid where each grid space can
17 /// contain static scenery and/or game entities which can move and interact
18 /// with other game entities.
22 // DEBUG: Tilesets not implemented at all.
23 public static Texture2D DefaultTile;
26 #region Public Constants
28 public const float PixelsToUnitSquares = 64.0f;
36 /// The type of a map helps determine how the map is intended to be used.
46 /// The container class for map metadata.
53 public HashSet<int> NumPlayers = new HashSet<int>();
54 public string Tileset;
56 public int GridHeight;
60 /// The container class for information about an entity defined in the map.
62 public class RawEntity
65 public Point Position;
66 public Dictionary<string, string> Attributes = new Dictionary<string, string>();
72 #region Public Properties
75 /// Get the name of the map.
77 public string Name { get { return mData.Metadata.Name; } }
80 /// Get the type of the map.
82 public Mode Type { get { return mData.Metadata.Type; } }
85 /// Get the author of the map.
87 public string Author { get { return mData.Metadata.Author; } }
90 /// Get a set of integers containing each allowable number of players.
92 public HashSet<int> NumPlayers { get { return mData.Metadata.NumPlayers; } }
95 /// Get the width of the map, in grid units.
97 public int Width { get { return mData.Metadata.GridWidth; } }
100 /// Get the height of the map, in grid units.
102 public int Height { get { return mData.Metadata.GridHeight; } }
104 // TODO: This should return whatever object we end up using for tilesets.
105 public string Tileset { get { return mData.Metadata.Tileset; } }
108 /// Get the current grid of open cells. On the grid, true means
109 /// the cell is open (i.e. an entity can occupy that cell), and false
110 /// means the cell is closed. Note that, just like Map.IsCellOpen,
111 /// only static scenery is considered; the grid cannot tell you
112 /// whether or not an entity is already occupying the cell.
114 public bool[,] Grid { get { return mData.Grid; } }
117 /// Get a list of the raw entity containers loaded with the map. If you
118 /// want to get the actual entity objects, use Map.GetEntities and
119 /// Map.GetAllEntities instead.
121 public List<RawEntity> RawEntities { get { return mData.Entities; } }
125 /// Get and set the coordinate of the grid cell that should be in
126 /// the center of the screen when the map is drawn. Setting this
127 /// will change the viewport of the map and will effect the return
128 /// values of Map.GetPointFromCoordinates and Map.GetRectangleFromCoordinates.
130 public Vector2 CenterCell
132 get { return mView.CenterCell; }
133 set { mView.CenterCell = value; }
137 /// Get and set the zoom of the map view. The default zoom is
138 /// Map.PixelsToUnitSquares.
142 get { return mView.Zoom; }
143 set { mView.Zoom = value; }
149 #region Public Methods
152 /// Construct a map with the provided map data.
154 /// <param name="metadata">The metadata.</param>
155 /// <param name="grid">The grid.</param>
156 /// <param name="entities">The entities.</param>
157 public Map(Metadata metadata, char[,] grid, char defaultTile,
158 List<RawEntity> entities, Point[] playerPositions)
160 mData = new Model(metadata, grid, defaultTile, entities, playerPositions);
161 mView = new View(mData);
166 /// Draw a representation of the map to the screen.
168 /// <param name="spriteBatch">The jeewiz.</param>
169 public void Draw(SpriteBatch spriteBatch)
171 mView.Draw(spriteBatch);
176 /// Get a point in screen-space from a coordinate in gridspace.
178 /// <param name="x">X-coordinate.</param>
179 /// <param name="y">Y-coordinate.</param>
180 /// <returns>Transformed point.</returns>
181 public Point GetPointFromCoordinates(float x, float y)
183 return mView.GetPointFromCoordinates(x, y);
187 /// Get a point in screen-space from a coordinate in gridspace.
189 /// <param name="point">X,Y-coordinates.</param>
190 /// <returns>Transformed point.</returns>
191 public Point GetPointFromCoordinates(Vector2 point)
193 return mView.GetPointFromCoordinates(point.X, point.Y);
197 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
199 /// <param name="x">X-coordinate.</param>
200 /// <param name="y">Y-coordinate.</param>
201 /// <returns>Transformed rectangle.</returns>
202 public Rectangle GetRectangleFromCoordinates(float x, float y)
204 return mView.GetRectangleFromCoordinates(x, y);
208 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
210 /// <param name="point">X,Y-coordinates.</param>
211 /// <returns>Transformed rectangle.</returns>
212 public Rectangle GetRectangleFromCoordinates(Vector2 point)
214 return mView.GetRectangleFromCoordinates(point.X, point.Y);
219 /// Determine whether or not a cell can be occupied by a game entity.
221 /// <param name="x">X-coordinate.</param>
222 /// <param name="y">Y-coordinate.</param>
223 /// <returns>True if cell can be occupied, false otherwise.</returns>
224 public bool IsCellOpen(int x, int y)
226 return mData.IsCellOpen(x, y);
230 /// Determine whether or not a cell can be occupied by a game entity.
232 /// <param name="point">X,Y-coordinates.</param>
233 /// <returns>True if cell can be occupied, false otherwise.</returns>
234 public bool IsCellOpen(Point point)
236 return mData.IsCellOpen(point.X, point.Y);
241 /// Get the starting position of a player.
243 /// <param name="playerNumber">The number of the player (i.e. 1-4).
244 /// This number must be a valid player number.</param>
245 /// <returns>The starting position of the player.</returns>
246 public Point GetStartingPositionForPlayer(int playerNumber)
248 Debug.Assert(1 <= playerNumber && playerNumber <= NumPlayers.Max());
249 return mData.PlayerPositions[playerNumber];
254 /// Get all the entities loaded from the map file. Exceptions could be
255 /// thrown if there are entities without associated classes.
257 /// <param name="game">The game reference to be passed to entities.</param>
258 /// <returns>List of entity objects loaded.</returns>
259 public List<IEntity> GetAllEntities(Game game)
261 return mData.GetAllEntities(game);
265 /// Get the entities of a certain type loaded from the map file. Exceptions
266 /// could be thrown if there are entities without associated classes.
268 /// <param name="game">The game reference to be passed to entities.</param>
269 /// <typeparam name="T">Type of the entity you want a list of.</typeparam>
270 /// <returns>List of entity objects loaded.</returns>
271 public List<T> GetEntities<T>(Game game)
273 return mData.GetEntities<T>(game);
278 /// Set the tile of a cell.
280 /// <param name="x">X-coordinate.</param>
281 /// <param name="y">Y-coordinate.</param>
282 /// <param name="tile">The character representing the tile.</param>
283 public void SetCell(int x, int y, char tile)
285 mData.SetCell(x, y, tile);
289 /// Set the tile of a cell.
291 /// <param name="point">X,Y-coordinates.</param>
292 /// <param name="tile">The character representing the tile.</param>
293 public void SetCell(Point point, char tile)
295 mData.SetCell(point.X, point.Y, tile);
300 /// Clear a cell to the default tile.
302 /// <param name="x">X-coordinate.</param>
303 /// <param name="y">Y-coordinate.</param>
304 public void ClearCell(int x, int y)
306 mData.ClearCell(x, y);
310 /// Clear a cell to the default tile.
312 /// <param name="point">X,Y-coordinates.</param>
313 public void ClearCell(Point point)
315 mData.ClearCell(point.X, point.Y);
320 /// Reset the map to the state it was at right after loading.
331 #region Private Types
335 public Metadata Metadata { get { return mMetadata; } }
336 public List<RawEntity> Entities { get { return mEntities; } }
337 public Point[] PlayerPositions { get { return mPlayerPositions; } }
338 public bool[,] Grid { get { return mBooleanGrid; } }
341 public Model(Metadata metadata, char[,] grid, char defaultTile,
342 List<RawEntity> entities, Point[] playerPositions)
344 Debug.Assert(metadata != null);
345 Debug.Assert(grid != null);
346 Debug.Assert(entities != null);
347 Debug.Assert(metadata.GridWidth * metadata.GridHeight == grid.Length);
349 mMetadata = metadata;
351 mDefaultTile = defaultTile;
352 mEntities = entities;
353 mPlayerPositions = playerPositions;
358 Console.WriteLine("Loaded map {0} of type {1} written by {2}.",
368 mGrid = (char[,])mCleanGrid.Clone();
370 mBooleanGrid = new bool[mMetadata.GridWidth, mMetadata.GridHeight];
371 for (int x = 0; x < mMetadata.GridWidth; x++)
373 for (int y = 0; y < mMetadata.GridHeight; y++)
375 mBooleanGrid[x, y] = IsCellOpen(x, y);
381 public bool IsCellOpen(int x, int y)
383 // TODO: Still need to define characters for types of scenery.
384 if (IsOnMap(x, y)) return mGrid[x, y] == ' ';
388 public void SetCell(int x, int y, char tile)
393 mBooleanGrid[x, y] = IsCellOpen(x, y);
397 public void ClearCell(int x, int y)
399 SetCell(x, y, mDefaultTile);
402 public bool IsOnMap(int x, int y)
404 return 0 <= x && x < Metadata.GridWidth && 0 <= y && y < Metadata.GridHeight;
408 public List<IEntity> GetAllEntities(Game game)
410 List<IEntity> list = new List<IEntity>();
412 foreach (RawEntity raw in mEntities)
414 if (raw.Attributes.ContainsKey("type"))
416 string typename = raw.Attributes["type"];
418 object[] args = new object[4];
420 args[1] = raw.Position;
421 args[2] = raw.Attributes;
426 IEntity entity = (IEntity)Activator.CreateInstance(System.Type.GetType("CarFire." + typename), args);
429 entity.LoadContent(game.ContentManager);
432 else throw new Exception();
434 #pragma warning disable 0168
435 catch (System.Exception ex)
436 #pragma warning restore 0168
438 throw new Exception("Entity of type " + typename + " not loaded because an entity class can't be found.");
443 Console.WriteLine("Ignoring entity with identifier " + raw.Id + " since it has no type key.");
450 public List<T> GetEntities<T>(Game game)
452 System.Type type = typeof(T);
453 List<T> list = new List<T>();
455 string typename = typeof(T).Name;
456 foreach (RawEntity raw in mEntities)
458 if (raw.Attributes.ContainsKey("type") && typename == raw.Attributes["type"])
460 object[] args = new object[4];
462 args[1] = raw.Position;
463 args[2] = raw.Attributes;
466 T entity = (T)Activator.CreateInstance(type, args);
469 ((IEntity)entity).LoadContent(game.ContentManager);
472 else throw new Exception("Entity of type " + typename + " not loaded because an entity class can't be found.");
483 bool[,] mBooleanGrid;
485 List<RawEntity> mEntities;
486 Point[] mPlayerPositions;
491 public Vector2 CenterCell;
495 public View(Model data)
497 Debug.Assert(data != null);
506 CenterCell = Vector2.Zero;
507 Zoom = PixelsToUnitSquares;
511 public void Draw(SpriteBatch spriteBatch)
513 mViewport = spriteBatch.GraphicsDevice.Viewport;
515 // TODO: There is no culling yet, but it runs so fast that it probably won't ever need it.
516 for (int y = 0; y < mData.Metadata.GridHeight; y++)
518 for (int x = 0; x < mData.Metadata.GridWidth; x++)
520 if (mData.IsCellOpen(x, y))
522 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.White);
526 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.DarkBlue);
533 public Point GetPointFromCoordinates(float x, float y)
535 Matrix transform = GetTransformation(CenterCell);
536 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
538 return new Point((int)point.X, (int)point.Y);
541 public Rectangle GetRectangleFromCoordinates(float x, float y)
543 Matrix transform = GetTransformation(CenterCell);
544 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
546 return new Rectangle((int)Math.Round(point.X, 0), (int)Math.Round(point.Y, 0), (int)Math.Round(Zoom, 0), (int)Math.Round(Zoom, 0));
551 Matrix GetTransformation(Vector2 center)
553 float halfRatio = Zoom * 0.5f;
554 Matrix transform = Matrix.CreateTranslation(-center.X, -center.Y, 0.0f);
555 transform *= Matrix.CreateScale(Zoom);
556 transform *= Matrix.CreateTranslation(mViewport.Width * 0.5f - halfRatio,
557 mViewport.Height * 0.5f - halfRatio, 0.0f);
559 Vector2 topLeft = Vector2.Transform(new Vector2(0.0f, 0.0f), transform);
560 topLeft.X = Math.Max(mViewport.X, topLeft.X);
561 topLeft.Y = Math.Max(mViewport.Y, topLeft.Y);
562 transform *= Matrix.CreateTranslation(-topLeft.X, -topLeft.Y, 0.0f);
564 Vector2 bottomRight = Vector2.Transform(new Vector2((float)mData.Metadata.GridWidth,
565 (float)mData.Metadata.GridHeight), transform);
566 float right = mViewport.X + mViewport.Width;
567 float bottom = mViewport.Y + mViewport.Height;
568 bottomRight.X = Math.Min(right, bottomRight.X) - right;
569 bottomRight.Y = Math.Min(bottom, bottomRight.Y) - bottom;
570 transform *= Matrix.CreateTranslation(-bottomRight.X, -bottomRight.Y, 0.0f);
583 #region Private Variables