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 #region Public Constants
24 public const float PixelsToUnitSquares = 64.0f;
32 /// The type of a map helps determine how the map is intended to be used.
42 /// The container class for map metadata.
50 public HashSet<int> NumPlayers = new HashSet<int>();
51 public string Tileset;
53 public int GridHeight;
57 /// The container class for information about an entity defined in the map.
59 public class RawEntity
62 public Point Position;
63 public Dictionary<string, string> Attributes = new Dictionary<string, string>();
69 #region Public Properties
72 /// Get the name of the map.
74 public string Name { get { return mData.Metadata.Name; } }
77 /// Get the type of the map.
79 public Mode Type { get { return mData.Metadata.Type; } }
82 /// Get the author of the map.
84 public string Author { get { return mData.Metadata.Author; } }
87 /// Get the name of the next map to load after this one.
89 public string Next { get { return mData.Metadata.Next; } }
92 /// Get a set of integers containing each allowable number of players.
94 public HashSet<int> NumPlayers { get { return mData.Metadata.NumPlayers; } }
97 /// Get the width of the map, in grid units.
99 public int Width { get { return mData.Metadata.GridWidth; } }
102 /// Get the height of the map, in grid units.
104 public int Height { get { return mData.Metadata.GridHeight; } }
107 /// Get the name of the tileset.
109 public string Tileset { get { return mData.Metadata.Tileset; } }
112 /// Get the current grid of open cells. On the grid, true means
113 /// the cell is open (i.e. an entity can occupy that cell), and false
114 /// means the cell is closed. Note that, just like Map.IsCellOpen,
115 /// only static scenery is considered; the grid cannot tell you
116 /// whether or not an entity is already occupying the cell.
118 public bool[,] Grid { get { return mData.Grid; } }
121 /// Get a list of the raw entity containers loaded with the map. If you
122 /// want to get the actual entity objects, use Map.GetEntities and
123 /// Map.GetAllEntities instead.
125 public List<RawEntity> RawEntities { get { return mData.Entities; } }
129 /// Get and set the coordinate of the grid cell that should be in
130 /// the center of the screen when the map is drawn. Setting this
131 /// will change the viewport of the map and will effect the return
132 /// values of Map.GetPointFromCoordinates and Map.GetRectangleFromCoordinates.
134 public Vector2 CenterCell
136 get { return mView.CenterCell; }
137 set { mView.CenterCell = value; }
141 /// Get and set the tilemap with its associated texture and tile
142 /// character to coordinate mappings. This effects what the map looks
143 /// like when it is drawn. You will need to reset any map instances
144 /// after setting a new tilemap. You should also set a tilemap before
145 /// instantiating any maps.
147 public static Tilemap Tilemap;
150 /// Get and set the zoom of the map view. The default zoom is
151 /// Map.PixelsToUnitSquares.
155 get { return mView.Zoom; }
156 set { mView.Zoom = 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 Model(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 /// created by Brady for AI precalculations
245 /// <param name="x">X-coordinate.</param>
246 /// <param name="y">Y-coordinate.</param>
247 public bool IsWall(int x, int y)
249 return mData.IsWall(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 /// <param name="game">The game reference to be passed to entities.</param>
281 /// <returns>List of entity objects loaded.</returns>
282 public List<IEntity> GetAllEntities(Game game)
284 return mData.GetAllEntities(game);
288 /// Get the entities of a certain type loaded from the map file. Exceptions
289 /// could be thrown if there are entities without associated classes.
291 /// <param name="game">The game reference to be passed to entities.</param>
292 /// <typeparam name="T">Type of the entity you want a list of.</typeparam>
293 /// <returns>List of entity objects loaded.</returns>
294 public List<T> GetEntities<T>(Game game)
296 return mData.GetEntities<T>(game);
301 /// Set the tile of a cell.
303 /// <param name="x">X-coordinate.</param>
304 /// <param name="y">Y-coordinate.</param>
305 /// <param name="tile">The character representing the tile.</param>
306 public void SetCell(int x, int y, char tile)
308 mData.SetCell(x, y, tile);
312 /// Set the tile of a cell.
314 /// <param name="point">X,Y-coordinates.</param>
315 /// <param name="tile">The character representing the tile.</param>
316 public void SetCell(Point point, char tile)
318 mData.SetCell(point.X, point.Y, tile);
323 /// Clear a cell to the default tile.
325 /// <param name="x">X-coordinate.</param>
326 /// <param name="y">Y-coordinate.</param>
327 public void ClearCell(int x, int y)
329 mData.ClearCell(x, y);
333 /// Clear a cell to the default tile.
335 /// <param name="point">X,Y-coordinates.</param>
336 public void ClearCell(Point point)
338 mData.ClearCell(point.X, point.Y);
343 /// Reset the map to the state it was at right after loading.
354 #region Private Types
358 public Metadata Metadata { get { return mMetadata; } }
359 public List<RawEntity> Entities { get { return mEntities; } }
360 public Point[] PlayerPositions { get { return mPlayerPositions; } }
361 public bool[,] Grid { get { return mBooleanGrid; } }
364 public Model(Metadata metadata, char[,] grid, char defaultTile,
365 List<RawEntity> entities, Point[] playerPositions)
367 Debug.Assert(metadata != null);
368 Debug.Assert(grid != null);
369 Debug.Assert(entities != null);
370 Debug.Assert(metadata.GridWidth * metadata.GridHeight == grid.Length);
371 Debug.Assert(Tilemap != null);
373 mMetadata = metadata;
375 mDefaultTile = defaultTile;
376 mEntities = entities;
377 mPlayerPositions = playerPositions;
382 Console.WriteLine("Loaded map {0} of type {1} written by {2}.",
392 mGrid = (char[,])mCleanGrid.Clone();
394 mBooleanGrid = new bool[mMetadata.GridWidth, mMetadata.GridHeight];
395 for (int x = 0; x < mMetadata.GridWidth; x++)
397 for (int y = 0; y < mMetadata.GridHeight; y++)
399 mBooleanGrid[x, y] = IsCellOpen(x, y);
405 public bool IsCellOpen(int x, int y)
407 if (!IsOnMap(x, y)) return false;
408 return (Tilemap.GetTileFlags(mGrid[x, y]) & TileFlags.Open) == TileFlags.Open;
411 //created by Brady for AI precalculations
412 public bool IsWall(int x, int y)
414 if (!IsOnMap(x, y)) return false;
415 return (Tilemap.GetTileFlags(mGrid[x, y]) & TileFlags.Wall) == TileFlags.Wall;
418 public void SetCell(int x, int y, char tile)
423 mBooleanGrid[x, y] = IsCellOpen(x, y);
427 public char GetCell(int x, int y)
429 if (IsOnMap(x, y)) return mGrid[x, y];
433 public void ClearCell(int x, int y)
435 SetCell(x, y, mDefaultTile);
438 public bool IsOnMap(int x, int y)
440 return 0 <= x && x < Metadata.GridWidth && 0 <= y && y < Metadata.GridHeight;
444 public List<IEntity> GetAllEntities(Game game)
446 List<IEntity> list = new List<IEntity>();
448 foreach (RawEntity raw in mEntities)
450 if (raw.Attributes.ContainsKey("type"))
452 string typename = raw.Attributes["type"];
454 object[] args = new object[4];
456 args[1] = raw.Position;
457 args[2] = raw.Attributes;
462 IEntity entity = (IEntity)Activator.CreateInstance(System.Type.GetType("CarFire." + typename), args);
465 entity.LoadContent(game.ContentManager);
468 else throw new Exception();
470 #pragma warning disable 0168
471 catch (System.Exception ex)
472 #pragma warning restore 0168
474 throw new Exception("Entity of type " + typename + " not loaded because an entity class can't be found.");
479 Console.WriteLine("Ignoring entity with identifier " + raw.Id + " since it has no type key.");
486 public List<T> GetEntities<T>(Game game)
488 System.Type type = typeof(T);
489 List<T> list = new List<T>();
491 string typename = typeof(T).Name;
492 foreach (RawEntity raw in mEntities)
494 if (raw.Attributes.ContainsKey("type") && typename == raw.Attributes["type"])
496 object[] args = new object[4];
498 args[1] = raw.Position;
499 args[2] = raw.Attributes;
502 T entity = (T)Activator.CreateInstance(type, args);
505 ((IEntity)entity).LoadContent(game.ContentManager);
508 else throw new Exception("Entity of type " + typename + " not loaded because an entity class can't be found.");
519 bool[,] mBooleanGrid;
521 List<RawEntity> mEntities;
522 Point[] mPlayerPositions;
527 public Vector2 CenterCell;
531 public View(Model data)
533 Debug.Assert(data != null);
542 CenterCell = Vector2.Zero;
543 Zoom = PixelsToUnitSquares;
547 public void Draw(SpriteBatch spriteBatch)
549 if (Tilemap == null) throw new Exception("Cannot draw map without first setting the tilemap.");
550 mViewport = spriteBatch.GraphicsDevice.Viewport;
552 for (int y = 0; y < mData.Metadata.GridHeight; y++)
554 for (int x = 0; x < mData.Metadata.GridWidth; x++)
556 Tilemap.Draw(spriteBatch, mData.GetCell(x, y), GetRectangleFromCoordinates(x, y));
562 public Point GetPointFromCoordinates(float x, float y)
564 Matrix transform = GetTransformation(CenterCell);
565 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
567 return new Point((int)point.X, (int)point.Y);
570 public Rectangle GetRectangleFromCoordinates(float x, float y)
572 Matrix transform = GetTransformation(CenterCell);
573 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
575 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));
580 Matrix GetTransformation(Vector2 center)
582 float halfRatio = Zoom * 0.5f;
583 Matrix transform = Matrix.CreateTranslation(-center.X, -center.Y, 0.0f);
584 transform *= Matrix.CreateScale(Zoom);
585 transform *= Matrix.CreateTranslation(mViewport.Width * 0.5f - halfRatio,
586 mViewport.Height * 0.5f - halfRatio, 0.0f);
588 Vector2 topLeft = Vector2.Transform(new Vector2(0.0f, 0.0f), transform);
589 topLeft.X = Math.Max(mViewport.X, topLeft.X);
590 topLeft.Y = Math.Max(mViewport.Y, topLeft.Y);
591 transform *= Matrix.CreateTranslation(-topLeft.X, -topLeft.Y, 0.0f);
593 Vector2 bottomRight = Vector2.Transform(new Vector2((float)mData.Metadata.GridWidth,
594 (float)mData.Metadata.GridHeight), transform);
595 float right = mViewport.X + mViewport.Width;
596 float bottom = mViewport.Y + mViewport.Height;
597 bottomRight.X = Math.Min(right, bottomRight.X) - right;
598 bottomRight.Y = Math.Min(bottom, bottomRight.Y) - bottom;
599 transform *= Matrix.CreateTranslation(-bottomRight.X, -bottomRight.Y, 0.0f);
612 #region Private Variables