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 a list of the raw entity containers loaded with the map.
133 public List<RawEntity> RawEntities { get { return mData.Entities; } }
137 /// Get and set the coordinate of the grid cell that should be in
138 /// the center of the screen when the map is drawn.
140 public Vector2 CenterCell
142 get { return mView.CenterCell; }
143 set { mView.CenterCell = 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, List<RawEntity> entities, Point[] playerPositions)
159 mData = new Modal(metadata, grid, entities, playerPositions);
160 mView = new View(mData);
165 /// Draw a representation of the map to the screen.
167 /// <param name="spriteBatch">The jeewiz.</param>
168 public void Draw(SpriteBatch spriteBatch)
170 mView.Draw(spriteBatch);
175 /// Get a point in screen-space from a coordinate in gridspace.
177 /// <param name="x">X-coordinate.</param>
178 /// <param name="y">Y-coordinate.</param>
179 /// <returns>Transformed point.</returns>
180 public Point GetPointFromCoordinates(float x, float y)
182 return mView.GetPointFromCoordinates(x, y);
186 /// Get a point in screen-space from a coordinate in gridspace.
188 /// <param name="point">X,Y-coordinates.</param>
189 /// <returns>Transformed point.</returns>
190 public Point GetPointFromCoordinates(Vector2 point)
192 return mView.GetPointFromCoordinates(point.X, point.Y);
196 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
198 /// <param name="x">X-coordinate.</param>
199 /// <param name="y">Y-coordinate.</param>
200 /// <returns>Transformed rectangle.</returns>
201 public Rectangle GetRectangleFromCoordinates(float x, float y)
203 return mView.GetRectangleFromCoordinates(x, y);
207 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
209 /// <param name="point">X,Y-coordinates.</param>
210 /// <returns>Transformed rectangle.</returns>
211 public Rectangle GetRectangleFromCoordinates(Vector2 point)
213 return mView.GetRectangleFromCoordinates(point.X, point.Y);
218 /// Determine whether or not a cell can be occupied by a game entity.
220 /// <param name="x">X-coordinate.</param>
221 /// <param name="y">Y-coordinate.</param>
222 /// <returns>True if cell can be occupied, false otherwise.</returns>
223 public bool IsCellOpen(int x, int y)
225 return mData.IsCellOpen(x, y);
229 /// Determine whether or not a cell can be occupied by a game entity.
231 /// <param name="point">X,Y-coordinates.</param>
232 /// <returns>True if cell can be occupied, false otherwise.</returns>
233 public bool IsCellOpen(Point point)
235 return mData.IsCellOpen(point.X, point.Y);
240 /// Get the starting position of a player.
242 /// <param name="playerNumber">The number of the player (i.e. 1-4).
243 /// This number must be a valid player number.</param>
244 /// <returns>The starting position of the player.</returns>
245 public Point GetStartingPositionForPlayer(int playerNumber)
247 Debug.Assert(1 <= playerNumber && playerNumber <= NumPlayers.Max());
248 return mData.PlayerPositions[playerNumber];
253 /// Get all the entities loaded from the map file. Exceptions could be
254 /// thrown if there are entities without associated classes.
256 /// <returns>List of entity objects loaded.</returns>
257 public List<object> GetAllEntities()
259 return mData.GetAllEntities();
263 /// Get the entities of a certain type loaded from the map file. Exceptions
264 /// could be thrown if there are entities without associated classes.
266 /// <typeparam name="T">Type of the entity you want a list of.</typeparam>
267 /// <returns>List of entity objects loaded.</returns>
268 public List<T> GetEntities<T>()
270 return mData.GetEntities<T>();
276 #region Private Types
282 List<RawEntity> mEntities;
283 Point[] mPlayerPositions;
285 public Modal(Metadata metadata, char[,] grid, List<RawEntity> entities, Point[] playerPositions)
287 Debug.Assert(metadata != null);
288 Debug.Assert(grid != null);
289 Debug.Assert(entities != null);
290 Debug.Assert(metadata.GridWidth * metadata.GridHeight == grid.Length);
292 mMetadata = metadata;
294 mEntities = entities;
295 mPlayerPositions = playerPositions;
298 Console.WriteLine("Loaded map {0} of type {1} written by {2}.",
306 public Metadata Metadata { get { return mMetadata; } }
307 public List<RawEntity> Entities { get { return mEntities; } }
308 public Point[] PlayerPositions { get { return mPlayerPositions; } }
311 public bool IsCellOpen(int x, int y)
313 // TODO: Still need to define characters for types of scenery.
314 return mGrid[x, y] == ' ';
318 public List<object> GetAllEntities()
320 List<object> list = new List<object>();
322 foreach (RawEntity raw in mEntities)
324 if (raw.Attributes.ContainsKey("type"))
326 string typename = raw.Attributes["type"];
328 object[] args = new object[3];
330 args[1] = raw.Position;
331 args[2] = raw.Attributes;
336 object entity = Activator.CreateInstance(System.Type.GetType("CarFire." + typename), args);
337 if (entity != null) list.Add(entity);
338 else throw new RuntimeException();
340 #pragma warning disable 0168
341 catch (System.Exception ex)
342 #pragma warning restore 0168
344 throw new RuntimeException("Entity of type " + typename + " not loaded because an entity class can't be found.");
349 Console.WriteLine("Ignoring entity with identifier " + raw.Id + " since it has no type key.");
356 public List<T> GetEntities<T>()
358 System.Type type = typeof(T);
359 List<T> list = new List<T>();
361 string typename = typeof(T).Name;
362 foreach (RawEntity raw in mEntities)
364 if (raw.Attributes.ContainsKey("type") && typename == raw.Attributes["type"])
366 object[] args = new object[3];
368 args[1] = raw.Position;
369 args[2] = raw.Attributes;
371 T entity = (T)Activator.CreateInstance(type, args);
372 if (entity != null) list.Add(entity);
373 else throw new RuntimeException("Entity of type " + typename + " not loaded because an entity class can't be found.");
385 public Vector2 CenterCell;
389 public View(Modal data)
391 Debug.Assert(data != null);
395 public void Draw(SpriteBatch spriteBatch)
397 mViewport = spriteBatch.GraphicsDevice.Viewport;
399 // TODO: There is no culling yet, but it runs so fast that it probably won't ever need it.
400 for (int y = 0; y < mData.Metadata.GridHeight; y++)
402 for (int x = 0; x < mData.Metadata.GridWidth; x++)
404 if (mData.IsCellOpen(x, y))
406 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.White);
410 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.DarkBlue);
417 /// Get a matrix to transform a point from grid-space to screen coordinates. This
418 /// method uses the viewport to bound the edges of the map such that the camera
419 /// will not show anything outside of the grid.
421 /// <param name="center">The point to put in the center.</param>
422 /// <returns>The transformation matrix.</returns>
423 Matrix GetTransformation(Vector2 center)
425 float halfRatio = PixelsToUnitSquares * 0.5f;
426 Matrix transform = Matrix.CreateTranslation(-center.X, -center.Y, 0.0f);
427 transform *= Matrix.CreateScale(PixelsToUnitSquares);
428 transform *= Matrix.CreateTranslation(mViewport.Width * 0.5f - halfRatio,
429 mViewport.Height * 0.5f - halfRatio, 0.0f);
431 Vector2 topLeft = Vector2.Transform(new Vector2(0.0f, 0.0f), transform);
432 topLeft.X = Math.Max(mViewport.X, topLeft.X);
433 topLeft.Y = Math.Max(mViewport.Y, topLeft.Y);
434 transform *= Matrix.CreateTranslation(-topLeft.X, -topLeft.Y, 0.0f);
436 Vector2 bottomRight = Vector2.Transform(new Vector2((float)mData.Metadata.GridWidth,
437 (float)mData.Metadata.GridHeight), transform);
438 float right = mViewport.X + mViewport.Width;
439 float bottom = mViewport.Y + mViewport.Height;
440 bottomRight.X = Math.Min(right, bottomRight.X) - right;
441 bottomRight.Y = Math.Min(bottom, bottomRight.Y) - bottom;
442 transform *= Matrix.CreateTranslation(-bottomRight.X, -bottomRight.Y, 0.0f);
448 public Point GetPointFromCoordinates(float x, float y)
450 Matrix transform = GetTransformation(CenterCell);
451 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
453 return new Point((int)point.X, (int)point.Y);
456 public Rectangle GetRectangleFromCoordinates(float x, float y)
458 Matrix transform = GetTransformation(CenterCell);
459 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
461 return new Rectangle((int)point.X, (int)point.Y, (int)PixelsToUnitSquares, (int)PixelsToUnitSquares);
468 #region Private Variables