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 = 64.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 Properties
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; }
160 /// Get and set the zoom of the map view. The default zoom is
161 /// Map.PixelsToUnitSquares.
165 get { return mView.Zoom; }
166 set { mView.Zoom = value; }
172 #region Public Methods
175 /// Construct a map with the provided map data.
177 /// <param name="metadata">The metadata.</param>
178 /// <param name="grid">The grid.</param>
179 /// <param name="entities">The entities.</param>
180 public Map(Metadata metadata, char[,] grid, char defaultTile,
181 List<RawEntity> entities, Point[] playerPositions)
183 mData = new Model(metadata, grid, defaultTile, entities, playerPositions);
184 mView = new View(mData);
189 /// Draw a representation of the map to the screen.
191 /// <param name="spriteBatch">The jeewiz.</param>
192 public void Draw(SpriteBatch spriteBatch)
194 mView.Draw(spriteBatch);
199 /// Get a point in screen-space from a coordinate in gridspace.
201 /// <param name="x">X-coordinate.</param>
202 /// <param name="y">Y-coordinate.</param>
203 /// <returns>Transformed point.</returns>
204 public Point GetPointFromCoordinates(float x, float y)
206 return mView.GetPointFromCoordinates(x, y);
210 /// Get a point in screen-space from a coordinate in gridspace.
212 /// <param name="point">X,Y-coordinates.</param>
213 /// <returns>Transformed point.</returns>
214 public Point GetPointFromCoordinates(Vector2 point)
216 return mView.GetPointFromCoordinates(point.X, point.Y);
220 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
222 /// <param name="x">X-coordinate.</param>
223 /// <param name="y">Y-coordinate.</param>
224 /// <returns>Transformed rectangle.</returns>
225 public Rectangle GetRectangleFromCoordinates(float x, float y)
227 return mView.GetRectangleFromCoordinates(x, y);
231 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
233 /// <param name="point">X,Y-coordinates.</param>
234 /// <returns>Transformed rectangle.</returns>
235 public Rectangle GetRectangleFromCoordinates(Vector2 point)
237 return mView.GetRectangleFromCoordinates(point.X, point.Y);
242 /// Determine whether or not a cell can be occupied by a game entity.
244 /// <param name="x">X-coordinate.</param>
245 /// <param name="y">Y-coordinate.</param>
246 /// <returns>True if cell can be occupied, false otherwise.</returns>
247 public bool IsCellOpen(int x, int y)
249 return mData.IsCellOpen(x, y);
253 /// Determine whether or not a cell can be occupied by a game entity.
255 /// <param name="point">X,Y-coordinates.</param>
256 /// <returns>True if cell can be occupied, false otherwise.</returns>
257 public bool IsCellOpen(Point point)
259 return mData.IsCellOpen(point.X, point.Y);
264 /// Get the starting position of a player.
266 /// <param name="playerNumber">The number of the player (i.e. 1-4).
267 /// This number must be a valid player number.</param>
268 /// <returns>The starting position of the player.</returns>
269 public Point GetStartingPositionForPlayer(int playerNumber)
271 Debug.Assert(1 <= playerNumber && playerNumber <= NumPlayers.Max());
272 return mData.PlayerPositions[playerNumber];
277 /// Get all the entities loaded from the map file. Exceptions could be
278 /// thrown if there are entities without associated classes.
280 /// <returns>List of entity objects loaded.</returns>
281 public List<object> GetAllEntities()
283 return mData.GetAllEntities();
287 /// Get the entities of a certain type loaded from the map file. Exceptions
288 /// could be thrown if there are entities without associated classes.
290 /// <typeparam name="T">Type of the entity you want a list of.</typeparam>
291 /// <returns>List of entity objects loaded.</returns>
292 public List<T> GetEntities<T>()
294 return mData.GetEntities<T>();
299 /// Set the tile of a cell.
301 /// <param name="x">X-coordinate.</param>
302 /// <param name="y">Y-coordinate.</param>
303 /// <param name="tile">The character representing the tile.</param>
304 public void SetCell(int x, int y, char tile)
306 mData.SetCell(x, y, tile);
310 /// Set the tile of a cell.
312 /// <param name="point">X,Y-coordinates.</param>
313 /// <param name="tile">The character representing the tile.</param>
314 public void SetCell(Point point, char tile)
316 mData.SetCell(point.X, point.Y, tile);
321 /// Clear a cell to the default tile.
323 /// <param name="x">X-coordinate.</param>
324 /// <param name="y">Y-coordinate.</param>
325 public void ClearCell(int x, int y)
327 mData.ClearCell(x, y);
331 /// Clear a cell to the default tile.
333 /// <param name="point">X,Y-coordinates.</param>
334 public void ClearCell(Point point)
336 mData.ClearCell(point.X, point.Y);
341 /// Reset the map to the state it was at right after loading.
352 #region Private Types
356 public Metadata Metadata { get { return mMetadata; } }
357 public List<RawEntity> Entities { get { return mEntities; } }
358 public Point[] PlayerPositions { get { return mPlayerPositions; } }
359 public bool[,] Grid { get { return mBooleanGrid; } }
362 public Model(Metadata metadata, char[,] grid, char defaultTile,
363 List<RawEntity> entities, Point[] playerPositions)
365 Debug.Assert(metadata != null);
366 Debug.Assert(grid != null);
367 Debug.Assert(entities != null);
368 Debug.Assert(metadata.GridWidth * metadata.GridHeight == grid.Length);
370 mMetadata = metadata;
372 mDefaultTile = defaultTile;
373 mEntities = entities;
374 mPlayerPositions = playerPositions;
379 Console.WriteLine("Loaded map {0} of type {1} written by {2}.",
389 mGrid = (char[,])mCleanGrid.Clone();
391 mBooleanGrid = new bool[mMetadata.GridWidth, mMetadata.GridHeight];
392 for (int x = 0; x < mMetadata.GridWidth; x++)
394 for (int y = 0; y < mMetadata.GridHeight; y++)
396 mBooleanGrid[x, y] = IsCellOpen(x, y);
402 public bool IsCellOpen(int x, int y)
404 // TODO: Still need to define characters for types of scenery.
405 if (IsOnMap(x, y)) return mGrid[x, y] == ' ';
409 public void SetCell(int x, int y, char tile)
414 mBooleanGrid[x, y] = IsCellOpen(x, y);
418 public void ClearCell(int x, int y)
420 SetCell(x, y, mDefaultTile);
423 public bool IsOnMap(int x, int y)
425 return 0 <= x && x < Metadata.GridWidth && 0 <= y && y < Metadata.GridHeight;
429 public List<object> GetAllEntities()
431 List<object> list = new List<object>();
433 foreach (RawEntity raw in mEntities)
435 if (raw.Attributes.ContainsKey("type"))
437 string typename = raw.Attributes["type"];
439 object[] args = new object[3];
441 args[1] = raw.Position;
442 args[2] = raw.Attributes;
447 object entity = Activator.CreateInstance(System.Type.GetType("CarFire." + typename), args);
448 if (entity != null) list.Add(entity);
449 else throw new RuntimeException();
451 #pragma warning disable 0168
452 catch (System.Exception ex)
453 #pragma warning restore 0168
455 throw new RuntimeException("Entity of type " + typename + " not loaded because an entity class can't be found.");
460 Console.WriteLine("Ignoring entity with identifier " + raw.Id + " since it has no type key.");
467 public List<T> GetEntities<T>()
469 System.Type type = typeof(T);
470 List<T> list = new List<T>();
472 string typename = typeof(T).Name;
473 foreach (RawEntity raw in mEntities)
475 if (raw.Attributes.ContainsKey("type") && typename == raw.Attributes["type"])
477 object[] args = new object[3];
479 args[1] = raw.Position;
480 args[2] = raw.Attributes;
482 T entity = (T)Activator.CreateInstance(type, args);
483 if (entity != null) list.Add(entity);
484 else throw new RuntimeException("Entity of type " + typename + " not loaded because an entity class can't be found.");
495 bool[,] mBooleanGrid;
497 List<RawEntity> mEntities;
498 Point[] mPlayerPositions;
503 public Vector2 CenterCell;
507 public View(Model data)
509 Debug.Assert(data != null);
518 CenterCell = Vector2.Zero;
519 Zoom = PixelsToUnitSquares;
523 public void Draw(SpriteBatch spriteBatch)
525 mViewport = spriteBatch.GraphicsDevice.Viewport;
527 // TODO: There is no culling yet, but it runs so fast that it probably won't ever need it.
528 for (int y = 0; y < mData.Metadata.GridHeight; y++)
530 for (int x = 0; x < mData.Metadata.GridWidth; x++)
532 if (mData.IsCellOpen(x, y))
534 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.White);
538 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.DarkBlue);
545 public Point GetPointFromCoordinates(float x, float y)
547 Matrix transform = GetTransformation(CenterCell);
548 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
550 return new Point((int)point.X, (int)point.Y);
553 public Rectangle GetRectangleFromCoordinates(float x, float y)
555 Matrix transform = GetTransformation(CenterCell);
556 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
558 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));
563 Matrix GetTransformation(Vector2 center)
565 float halfRatio = Zoom * 0.5f;
566 Matrix transform = Matrix.CreateTranslation(-center.X, -center.Y, 0.0f);
567 transform *= Matrix.CreateScale(Zoom);
568 transform *= Matrix.CreateTranslation(mViewport.Width * 0.5f - halfRatio,
569 mViewport.Height * 0.5f - halfRatio, 0.0f);
571 Vector2 topLeft = Vector2.Transform(new Vector2(0.0f, 0.0f), transform);
572 topLeft.X = Math.Max(mViewport.X, topLeft.X);
573 topLeft.Y = Math.Max(mViewport.Y, topLeft.Y);
574 transform *= Matrix.CreateTranslation(-topLeft.X, -topLeft.Y, 0.0f);
576 Vector2 bottomRight = Vector2.Transform(new Vector2((float)mData.Metadata.GridWidth,
577 (float)mData.Metadata.GridHeight), transform);
578 float right = mViewport.X + mViewport.Width;
579 float bottom = mViewport.Y + mViewport.Height;
580 bottomRight.X = Math.Min(right, bottomRight.X) - right;
581 bottomRight.Y = Math.Min(bottom, bottomRight.Y) - bottom;
582 transform *= Matrix.CreateTranslation(-bottomRight.X, -bottomRight.Y, 0.0f);
595 #region Private Variables