]> Dogcows Code - chaz/carfire/blob - CarFire/CarFire/CarFire/Map.cs
git-svn-id: https://bd85.net/svn/cs3505_group@168 92bb83a3-7c8f-8a45-bc97-515c4e399668
[chaz/carfire] / CarFire / CarFire / CarFire / Map.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.IO;
6 using System.Runtime.Serialization;
7 using System.Diagnostics;
8 using Microsoft.Xna.Framework;
9 using Microsoft.Xna.Framework.Graphics;
10 using System.Reflection;
11
12 namespace CarFire
13 {
14 /// <summary>
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.
19 /// </summary>
20 public class Map
21 {
22 #region Public Constants
23
24 public const float PixelsToUnitSquares = 64.0f;
25
26 #endregion
27
28
29 #region Public Types
30
31 /// <summary>
32 /// The type of a map helps determine how the map is intended to be used.
33 /// </summary>
34 public enum Mode
35 {
36 None,
37 Campaign,
38 Battle
39 }
40
41 /// <summary>
42 /// The container class for map metadata.
43 /// </summary>
44 public class Metadata
45 {
46 public string Name;
47 public Mode Type;
48 public string Author;
49 public string Next;
50 public HashSet<int> NumPlayers = new HashSet<int>();
51 public string Tileset;
52 public int GridWidth;
53 public int GridHeight;
54 }
55
56 /// <summary>
57 /// The container class for information about an entity defined in the map.
58 /// </summary>
59 public class RawEntity
60 {
61 public char Id;
62 public Point Position;
63 public Dictionary<string, string> Attributes = new Dictionary<string, string>();
64 }
65
66 #endregion
67
68
69 #region Public Properties
70
71 /// <summary>
72 /// Get the name of the map.
73 /// </summary>
74 public string Name { get { return mData.Metadata.Name; } }
75
76 /// <summary>
77 /// Get the type of the map.
78 /// </summary>
79 public Mode Type { get { return mData.Metadata.Type; } }
80
81 /// <summary>
82 /// Get the author of the map.
83 /// </summary>
84 public string Author { get { return mData.Metadata.Author; } }
85
86 /// <summary>
87 /// Get the name of the next map to load after this one.
88 /// </summary>
89 public string Next { get { return mData.Metadata.Next; } }
90
91 /// <summary>
92 /// Get a set of integers containing each allowable number of players.
93 /// </summary>
94 public HashSet<int> NumPlayers { get { return mData.Metadata.NumPlayers; } }
95
96 /// <summary>
97 /// Get the width of the map, in grid units.
98 /// </summary>
99 public int Width { get { return mData.Metadata.GridWidth; } }
100
101 /// <summary>
102 /// Get the height of the map, in grid units.
103 /// </summary>
104 public int Height { get { return mData.Metadata.GridHeight; } }
105
106 /// <summary>
107 /// Get the name of the tileset.
108 /// </summary>
109 public string Tileset { get { return mData.Metadata.Tileset; } }
110
111 /// <summary>
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.
117 /// </summary>
118 public bool[,] Grid { get { return mData.Grid; } }
119
120 /// <summary>
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.
124 /// </summary>
125 public List<RawEntity> RawEntities { get { return mData.Entities; } }
126
127
128 /// <summary>
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.
133 /// </summary>
134 public Vector2 CenterCell
135 {
136 get { return mView.CenterCell; }
137 set { mView.CenterCell = value; }
138 }
139
140 /// <summary>
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.
146 /// </summary>
147 public static Tilemap Tilemap;
148
149 /// <summary>
150 /// Get and set the zoom of the map view. The default zoom is
151 /// Map.PixelsToUnitSquares.
152 /// </summary>
153 public float Zoom
154 {
155 get { return mView.Zoom; }
156 set { mView.Zoom = value; }
157 }
158
159 #endregion
160
161
162 #region Public Methods
163
164 /// <summary>
165 /// Construct a map with the provided map data.
166 /// </summary>
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)
172 {
173 mData = new Model(metadata, grid, defaultTile, entities, playerPositions);
174 mView = new View(mData);
175 }
176
177
178 /// <summary>
179 /// Draw a representation of the map to the screen.
180 /// </summary>
181 /// <param name="spriteBatch">The jeewiz.</param>
182 public void Draw(SpriteBatch spriteBatch)
183 {
184 mView.Draw(spriteBatch);
185 }
186
187
188 /// <summary>
189 /// Get a point in screen-space from a coordinate in gridspace.
190 /// </summary>
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)
195 {
196 return mView.GetPointFromCoordinates(x, y);
197 }
198
199 /// <summary>
200 /// Get a point in screen-space from a coordinate in gridspace.
201 /// </summary>
202 /// <param name="point">X,Y-coordinates.</param>
203 /// <returns>Transformed point.</returns>
204 public Point GetPointFromCoordinates(Vector2 point)
205 {
206 return mView.GetPointFromCoordinates(point.X, point.Y);
207 }
208
209 /// <summary>
210 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
211 /// </summary>
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)
216 {
217 return mView.GetRectangleFromCoordinates(x, y);
218 }
219
220 /// <summary>
221 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
222 /// </summary>
223 /// <param name="point">X,Y-coordinates.</param>
224 /// <returns>Transformed rectangle.</returns>
225 public Rectangle GetRectangleFromCoordinates(Vector2 point)
226 {
227 return mView.GetRectangleFromCoordinates(point.X, point.Y);
228 }
229
230
231 /// <summary>
232 /// Determine whether or not a cell can be occupied by a game entity.
233 /// </summary>
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)
238 {
239 return mData.IsCellOpen(x, y);
240 }
241
242 /// <summary>
243 /// created by Brady for AI precalculations
244 /// </summary>
245 /// <param name="x">X-coordinate.</param>
246 /// <param name="y">Y-coordinate.</param>
247 public bool IsWall(int x, int y)
248 {
249 return mData.IsWall(x, y);
250 }
251
252 /// <summary>
253 /// Determine whether or not a cell can be occupied by a game entity.
254 /// </summary>
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)
258 {
259 return mData.IsCellOpen(point.X, point.Y);
260 }
261
262
263 /// <summary>
264 /// Get the starting position of a player.
265 /// </summary>
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)
270 {
271 Debug.Assert(1 <= playerNumber && playerNumber <= NumPlayers.Max());
272 return mData.PlayerPositions[playerNumber];
273 }
274
275
276 /// <summary>
277 /// Get all the entities loaded from the map file. Exceptions could be
278 /// thrown if there are entities without associated classes.
279 /// </summary>
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)
283 {
284 return mData.GetAllEntities(game);
285 }
286
287 /// <summary>
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.
290 /// </summary>
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)
295 {
296 return mData.GetEntities<T>(game);
297 }
298
299
300 /// <summary>
301 /// Set the tile of a cell.
302 /// </summary>
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)
307 {
308 mData.SetCell(x, y, tile);
309 }
310
311 /// <summary>
312 /// Set the tile of a cell.
313 /// </summary>
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)
317 {
318 mData.SetCell(point.X, point.Y, tile);
319 }
320
321
322 /// <summary>
323 /// Clear a cell to the default tile.
324 /// </summary>
325 /// <param name="x">X-coordinate.</param>
326 /// <param name="y">Y-coordinate.</param>
327 public void ClearCell(int x, int y)
328 {
329 mData.ClearCell(x, y);
330 }
331
332 /// <summary>
333 /// Clear a cell to the default tile.
334 /// </summary>
335 /// <param name="point">X,Y-coordinates.</param>
336 public void ClearCell(Point point)
337 {
338 mData.ClearCell(point.X, point.Y);
339 }
340
341
342 /// <summary>
343 /// Reset the map to the state it was at right after loading.
344 /// </summary>
345 public void Reset()
346 {
347 mData.Reset();
348 mView.Reset();
349 }
350
351 #endregion
352
353
354 #region Private Types
355
356 class Model
357 {
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; } }
362
363
364 public Model(Metadata metadata, char[,] grid, char defaultTile,
365 List<RawEntity> entities, Point[] playerPositions)
366 {
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);
372
373 mMetadata = metadata;
374 mCleanGrid = grid;
375 mDefaultTile = defaultTile;
376 mEntities = entities;
377 mPlayerPositions = playerPositions;
378
379 Reset();
380
381 #if DEBUG
382 Console.WriteLine("Loaded map {0} of type {1} written by {2}.",
383 metadata.Name,
384 metadata.Type,
385 metadata.Author);
386 #endif
387 }
388
389
390 public void Reset()
391 {
392 mGrid = (char[,])mCleanGrid.Clone();
393
394 mBooleanGrid = new bool[mMetadata.GridWidth, mMetadata.GridHeight];
395 for (int x = 0; x < mMetadata.GridWidth; x++)
396 {
397 for (int y = 0; y < mMetadata.GridHeight; y++)
398 {
399 mBooleanGrid[x, y] = IsCellOpen(x, y);
400 }
401 }
402 }
403
404
405 public bool IsCellOpen(int x, int y)
406 {
407 if (!IsOnMap(x, y)) return false;
408 return (Tilemap.GetTileFlags(mGrid[x, y]) & TileFlags.Open) == TileFlags.Open;
409 }
410
411 //created by Brady for AI precalculations
412 public bool IsWall(int x, int y)
413 {
414 if (!IsOnMap(x, y)) return false;
415 return (Tilemap.GetTileFlags(mGrid[x, y]) & TileFlags.Wall) == TileFlags.Wall;
416 }
417
418 public void SetCell(int x, int y, char tile)
419 {
420 if (IsOnMap(x, y))
421 {
422 mGrid[x, y] = tile;
423 mBooleanGrid[x, y] = IsCellOpen(x, y);
424 }
425 }
426
427 public char GetCell(int x, int y)
428 {
429 if (IsOnMap(x, y)) return mGrid[x, y];
430 return mDefaultTile;
431 }
432
433 public void ClearCell(int x, int y)
434 {
435 SetCell(x, y, mDefaultTile);
436 }
437
438 public bool IsOnMap(int x, int y)
439 {
440 return 0 <= x && x < Metadata.GridWidth && 0 <= y && y < Metadata.GridHeight;
441 }
442
443
444 public List<IEntity> GetAllEntities(Game game)
445 {
446 List<IEntity> list = new List<IEntity>();
447
448 foreach (RawEntity raw in mEntities)
449 {
450 if (raw.Attributes.ContainsKey("type"))
451 {
452 string typename = raw.Attributes["type"];
453
454 object[] args = new object[4];
455 args[0] = raw.Id;
456 args[1] = raw.Position;
457 args[2] = raw.Attributes;
458 args[3] = game;
459
460 try
461 {
462 IEntity entity = (IEntity)Activator.CreateInstance(System.Type.GetType("CarFire." + typename), args);
463 if (entity != null)
464 {
465 entity.LoadContent(game.ContentManager);
466 list.Add(entity);
467 }
468 else throw new Exception();
469 }
470 #pragma warning disable 0168
471 catch (System.Exception ex)
472 #pragma warning restore 0168
473 {
474 throw new Exception("Entity of type " + typename + " not loaded because an entity class can't be found.");
475 }
476 }
477 else
478 {
479 Console.WriteLine("Ignoring entity with identifier " + raw.Id + " since it has no type key.");
480 }
481 }
482
483 return list;
484 }
485
486 public List<T> GetEntities<T>(Game game)
487 {
488 System.Type type = typeof(T);
489 List<T> list = new List<T>();
490
491 string typename = typeof(T).Name;
492 foreach (RawEntity raw in mEntities)
493 {
494 if (raw.Attributes.ContainsKey("type") && typename == raw.Attributes["type"])
495 {
496 object[] args = new object[4];
497 args[0] = raw.Id;
498 args[1] = raw.Position;
499 args[2] = raw.Attributes;
500 args[3] = game;
501
502 T entity = (T)Activator.CreateInstance(type, args);
503 if (entity != null)
504 {
505 ((IEntity)entity).LoadContent(game.ContentManager);
506 list.Add(entity);
507 }
508 else throw new Exception("Entity of type " + typename + " not loaded because an entity class can't be found.");
509 }
510 }
511
512 return list;
513 }
514
515
516 Metadata mMetadata;
517 char[,] mGrid;
518 char[,] mCleanGrid;
519 bool[,] mBooleanGrid;
520 char mDefaultTile;
521 List<RawEntity> mEntities;
522 Point[] mPlayerPositions;
523 }
524
525 class View
526 {
527 public Vector2 CenterCell;
528 public float Zoom;
529
530
531 public View(Model data)
532 {
533 Debug.Assert(data != null);
534 mData = data;
535
536 Reset();
537 }
538
539
540 public void Reset()
541 {
542 CenterCell = Vector2.Zero;
543 Zoom = PixelsToUnitSquares;
544 }
545
546
547 public void Draw(SpriteBatch spriteBatch)
548 {
549 if (Tilemap == null) throw new Exception("Cannot draw map without first setting the tilemap.");
550 mViewport = spriteBatch.GraphicsDevice.Viewport;
551
552 for (int y = 0; y < mData.Metadata.GridHeight; y++)
553 {
554 for (int x = 0; x < mData.Metadata.GridWidth; x++)
555 {
556 Tilemap.Draw(spriteBatch, mData.GetCell(x, y), GetRectangleFromCoordinates(x, y));
557 }
558 }
559 }
560
561
562 public Point GetPointFromCoordinates(float x, float y)
563 {
564 Matrix transform = GetTransformation(CenterCell);
565 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
566
567 return new Point((int)point.X, (int)point.Y);
568 }
569
570 public Rectangle GetRectangleFromCoordinates(float x, float y)
571 {
572 Matrix transform = GetTransformation(CenterCell);
573 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
574
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));
576 }
577
578
579
580 Matrix GetTransformation(Vector2 center)
581 {
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);
587
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);
592
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);
600
601 return transform;
602 }
603
604
605 Model mData;
606 Viewport mViewport;
607 }
608
609 #endregion
610
611
612 #region Private Variables
613
614 Model mData;
615 View mView;
616
617 #endregion
618 }
619 }
This page took 0.057285 seconds and 4 git commands to generate.