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;
25 #region Public Exceptions
28 /// This exception is thrown during the loading of a map if any
29 /// part of the map file is inconsistent with the expected format
32 public class RuntimeException : System.ApplicationException
34 public RuntimeException() { }
36 public RuntimeException(string message) :
39 public RuntimeException(string message, System.Exception inner) :
40 base(message, inner) { }
42 protected RuntimeException(SerializationInfo info, StreamingContext context) :
43 base(info, context) { }
49 #region Public Constants
51 public const float PixelsToUnitSquares = 60.0f;
59 /// The type of a map helps determine how the map is intended to be used.
69 /// The container class for map metadata.
76 public HashSet<int> NumPlayers = new HashSet<int>();
77 public string Tileset;
79 public int GridHeight;
83 /// The container class for information about an entity defined in the map.
85 public class RawEntity
88 public Point Position;
89 public Dictionary<string, string> Attributes = new Dictionary<string, string>();
95 #region Public Attributes
98 /// Get the name of the map.
100 public string Name { get { return mData.Metadata.Name; } }
103 /// Get the type of the map.
105 public Mode Type { get { return mData.Metadata.Type; } }
108 /// Get the author of the map.
110 public string Author { get { return mData.Metadata.Author; } }
113 /// Get a set of integers containing each allowable number of players.
115 public HashSet<int> NumPlayers { get { return mData.Metadata.NumPlayers; } }
118 /// Get the width of the map, in grid units.
120 public int Width { get { return mData.Metadata.GridWidth; } }
123 /// Get the height of the map, in grid units.
125 public int Height { get { return mData.Metadata.GridHeight; } }
127 // TODO: This should return whatever object we end up using for tilesets.
128 public string Tileset { get { return mData.Metadata.Tileset; } }
131 /// Get the current grid of open cells. On the grid, true means
132 /// the cell is open (i.e. an entity can occupy that cell), and false
133 /// means the cell is closed. Note that, just like Map.IsCellOpen,
134 /// only static scenery is considered; the grid cannot tell you
135 /// whether or not an entity is already occupying the cell.
137 public bool[,] Grid { get { return mData.Grid; } }
140 /// Get a list of the raw entity containers loaded with the map. If you
141 /// want to get the actual entity objects, use Map.GetEntities and
142 /// Map.GetAllEntities instead.
144 public List<RawEntity> RawEntities { get { return mData.Entities; } }
148 /// Get and set the coordinate of the grid cell that should be in
149 /// the center of the screen when the map is drawn. Setting this
150 /// will change the viewport of the map and will effect the return
151 /// values of Map.GetPointFromCoordinates and Map.GetRectangleFromCoordinates.
153 public Vector2 CenterCell
155 get { return mView.CenterCell; }
156 set { mView.CenterCell = value; }
162 #region Public Methods
165 /// Construct a map with the provided map data.
167 /// <param name="metadata">The metadata.</param>
168 /// <param name="grid">The grid.</param>
169 /// <param name="entities">The entities.</param>
170 public Map(Metadata metadata, char[,] grid, char defaultTile,
171 List<RawEntity> entities, Point[] playerPositions)
173 mData = new Modal(metadata, grid, defaultTile, entities, playerPositions);
174 mView = new View(mData);
179 /// Draw a representation of the map to the screen.
181 /// <param name="spriteBatch">The jeewiz.</param>
182 public void Draw(SpriteBatch spriteBatch)
184 mView.Draw(spriteBatch);
189 /// Get a point in screen-space from a coordinate in gridspace.
191 /// <param name="x">X-coordinate.</param>
192 /// <param name="y">Y-coordinate.</param>
193 /// <returns>Transformed point.</returns>
194 public Point GetPointFromCoordinates(float x, float y)
196 return mView.GetPointFromCoordinates(x, y);
200 /// Get a point in screen-space from a coordinate in gridspace.
202 /// <param name="point">X,Y-coordinates.</param>
203 /// <returns>Transformed point.</returns>
204 public Point GetPointFromCoordinates(Vector2 point)
206 return mView.GetPointFromCoordinates(point.X, point.Y);
210 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
212 /// <param name="x">X-coordinate.</param>
213 /// <param name="y">Y-coordinate.</param>
214 /// <returns>Transformed rectangle.</returns>
215 public Rectangle GetRectangleFromCoordinates(float x, float y)
217 return mView.GetRectangleFromCoordinates(x, y);
221 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
223 /// <param name="point">X,Y-coordinates.</param>
224 /// <returns>Transformed rectangle.</returns>
225 public Rectangle GetRectangleFromCoordinates(Vector2 point)
227 return mView.GetRectangleFromCoordinates(point.X, point.Y);
232 /// Determine whether or not a cell can be occupied by a game entity.
234 /// <param name="x">X-coordinate.</param>
235 /// <param name="y">Y-coordinate.</param>
236 /// <returns>True if cell can be occupied, false otherwise.</returns>
237 public bool IsCellOpen(int x, int y)
239 return mData.IsCellOpen(x, y);
243 /// Determine whether or not a cell can be occupied by a game entity.
245 /// <param name="point">X,Y-coordinates.</param>
246 /// <returns>True if cell can be occupied, false otherwise.</returns>
247 public bool IsCellOpen(Point point)
249 return mData.IsCellOpen(point.X, point.Y);
254 /// Get the starting position of a player.
256 /// <param name="playerNumber">The number of the player (i.e. 1-4).
257 /// This number must be a valid player number.</param>
258 /// <returns>The starting position of the player.</returns>
259 public Point GetStartingPositionForPlayer(int playerNumber)
261 Debug.Assert(1 <= playerNumber && playerNumber <= NumPlayers.Max());
262 return mData.PlayerPositions[playerNumber];
267 /// Get all the entities loaded from the map file. Exceptions could be
268 /// thrown if there are entities without associated classes.
270 /// <returns>List of entity objects loaded.</returns>
271 public List<object> GetAllEntities()
273 return mData.GetAllEntities();
277 /// Get the entities of a certain type loaded from the map file. Exceptions
278 /// could be thrown if there are entities without associated classes.
280 /// <typeparam name="T">Type of the entity you want a list of.</typeparam>
281 /// <returns>List of entity objects loaded.</returns>
282 public List<T> GetEntities<T>()
284 return mData.GetEntities<T>();
289 /// Set the tile of a cell.
291 /// <param name="x">X-coordinate.</param>
292 /// <param name="y">Y-coordinate.</param>
293 /// <param name="tile">The character representing the tile.</param>
294 public void SetCell(int x, int y, char tile)
296 mData.SetCell(x, y, tile);
300 /// Set the tile of a cell.
302 /// <param name="point">X,Y-coordinates.</param>
303 /// <param name="tile">The character representing the tile.</param>
304 public void SetCell(Point point, char tile)
306 mData.SetCell(point.X, point.Y, tile);
311 /// Clear a cell to the default tile.
313 /// <param name="x">X-coordinate.</param>
314 /// <param name="y">Y-coordinate.</param>
315 public void ClearCell(int x, int y)
317 mData.ClearCell(x, y);
321 /// Clear a cell to the default tile.
323 /// <param name="point">X,Y-coordinates.</param>
324 public void ClearCell(Point point)
326 mData.ClearCell(point.X, point.Y);
332 #region Private Types
339 List<RawEntity> mEntities;
340 Point[] mPlayerPositions;
341 bool[,] mBooleanGrid;
343 public Modal(Metadata metadata, char[,] grid, char defaultTile,
344 List<RawEntity> entities, Point[] playerPositions)
346 Debug.Assert(metadata != null);
347 Debug.Assert(grid != null);
348 Debug.Assert(entities != null);
349 Debug.Assert(metadata.GridWidth * metadata.GridHeight == grid.Length);
351 mMetadata = metadata;
353 mDefaultTile = defaultTile;
354 mEntities = entities;
355 mPlayerPositions = playerPositions;
357 mBooleanGrid = new bool[mMetadata.GridWidth, mMetadata.GridHeight];
358 for (int x = 0; x < mMetadata.GridWidth; x++)
360 for (int y = 0; y < mMetadata.GridHeight; y++)
362 mBooleanGrid[x, y] = IsCellOpen(x, y);
367 Console.WriteLine("Loaded map {0} of type {1} written by {2}.",
375 public Metadata Metadata { get { return mMetadata; } }
376 public List<RawEntity> Entities { get { return mEntities; } }
377 public Point[] PlayerPositions { get { return mPlayerPositions; } }
378 public bool[,] Grid { get { return mBooleanGrid; } }
381 public bool IsCellOpen(int x, int y)
383 // TODO: Still need to define characters for types of scenery.
384 return mGrid[x, y] == ' ';
387 public void SetCell(int x, int y, char tile)
390 mBooleanGrid[x, y] = IsCellOpen(x, y);
393 public void ClearCell(int x, int y)
395 SetCell(x, y, mDefaultTile);
399 public List<object> GetAllEntities()
401 List<object> list = new List<object>();
403 foreach (RawEntity raw in mEntities)
405 if (raw.Attributes.ContainsKey("type"))
407 string typename = raw.Attributes["type"];
409 object[] args = new object[3];
411 args[1] = raw.Position;
412 args[2] = raw.Attributes;
417 object entity = Activator.CreateInstance(System.Type.GetType("CarFire." + typename), args);
418 if (entity != null) list.Add(entity);
419 else throw new RuntimeException();
421 #pragma warning disable 0168
422 catch (System.Exception ex)
423 #pragma warning restore 0168
425 throw new RuntimeException("Entity of type " + typename + " not loaded because an entity class can't be found.");
430 Console.WriteLine("Ignoring entity with identifier " + raw.Id + " since it has no type key.");
437 public List<T> GetEntities<T>()
439 System.Type type = typeof(T);
440 List<T> list = new List<T>();
442 string typename = typeof(T).Name;
443 foreach (RawEntity raw in mEntities)
445 if (raw.Attributes.ContainsKey("type") && typename == raw.Attributes["type"])
447 object[] args = new object[3];
449 args[1] = raw.Position;
450 args[2] = raw.Attributes;
452 T entity = (T)Activator.CreateInstance(type, args);
453 if (entity != null) list.Add(entity);
454 else throw new RuntimeException("Entity of type " + typename + " not loaded because an entity class can't be found.");
466 public Vector2 CenterCell;
470 public View(Modal data)
472 Debug.Assert(data != null);
476 public void Draw(SpriteBatch spriteBatch)
478 mViewport = spriteBatch.GraphicsDevice.Viewport;
480 // TODO: There is no culling yet, but it runs so fast that it probably won't ever need it.
481 for (int y = 0; y < mData.Metadata.GridHeight; y++)
483 for (int x = 0; x < mData.Metadata.GridWidth; x++)
485 if (mData.IsCellOpen(x, y))
487 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.White);
491 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.DarkBlue);
498 /// Get a matrix to transform a point from grid-space to screen coordinates. This
499 /// method uses the viewport to bound the edges of the map such that the camera
500 /// will not show anything outside of the grid.
502 /// <param name="center">The point to put in the center.</param>
503 /// <returns>The transformation matrix.</returns>
504 Matrix GetTransformation(Vector2 center)
506 float halfRatio = PixelsToUnitSquares * 0.5f;
507 Matrix transform = Matrix.CreateTranslation(-center.X, -center.Y, 0.0f);
508 transform *= Matrix.CreateScale(PixelsToUnitSquares);
509 transform *= Matrix.CreateTranslation(mViewport.Width * 0.5f - halfRatio,
510 mViewport.Height * 0.5f - halfRatio, 0.0f);
512 Vector2 topLeft = Vector2.Transform(new Vector2(0.0f, 0.0f), transform);
513 topLeft.X = Math.Max(mViewport.X, topLeft.X);
514 topLeft.Y = Math.Max(mViewport.Y, topLeft.Y);
515 transform *= Matrix.CreateTranslation(-topLeft.X, -topLeft.Y, 0.0f);
517 Vector2 bottomRight = Vector2.Transform(new Vector2((float)mData.Metadata.GridWidth,
518 (float)mData.Metadata.GridHeight), transform);
519 float right = mViewport.X + mViewport.Width;
520 float bottom = mViewport.Y + mViewport.Height;
521 bottomRight.X = Math.Min(right, bottomRight.X) - right;
522 bottomRight.Y = Math.Min(bottom, bottomRight.Y) - bottom;
523 transform *= Matrix.CreateTranslation(-bottomRight.X, -bottomRight.Y, 0.0f);
529 public Point GetPointFromCoordinates(float x, float y)
531 Matrix transform = GetTransformation(CenterCell);
532 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
534 return new Point((int)point.X, (int)point.Y);
537 public Rectangle GetRectangleFromCoordinates(float x, float y)
539 Matrix transform = GetTransformation(CenterCell);
540 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
542 return new Rectangle((int)point.X, (int)point.Y, (int)PixelsToUnitSquares, (int)PixelsToUnitSquares);
549 #region Private Variables