]> Dogcows Code - chaz/carfire/blob - CarFire/CarFire/CarFire/Map.cs
Implemented tile flags so we can define and determine what a tile is supposed to...
[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 HashSet<int> NumPlayers = new HashSet<int>();
50 public string Tileset;
51 public int GridWidth;
52 public int GridHeight;
53 }
54
55 /// <summary>
56 /// The container class for information about an entity defined in the map.
57 /// </summary>
58 public class RawEntity
59 {
60 public char Id;
61 public Point Position;
62 public Dictionary<string, string> Attributes = new Dictionary<string, string>();
63 }
64
65 #endregion
66
67
68 #region Public Properties
69
70 /// <summary>
71 /// Get the name of the map.
72 /// </summary>
73 public string Name { get { return mData.Metadata.Name; } }
74
75 /// <summary>
76 /// Get the type of the map.
77 /// </summary>
78 public Mode Type { get { return mData.Metadata.Type; } }
79
80 /// <summary>
81 /// Get the author of the map.
82 /// </summary>
83 public string Author { get { return mData.Metadata.Author; } }
84
85 /// <summary>
86 /// Get a set of integers containing each allowable number of players.
87 /// </summary>
88 public HashSet<int> NumPlayers { get { return mData.Metadata.NumPlayers; } }
89
90 /// <summary>
91 /// Get the width of the map, in grid units.
92 /// </summary>
93 public int Width { get { return mData.Metadata.GridWidth; } }
94
95 /// <summary>
96 /// Get the height of the map, in grid units.
97 /// </summary>
98 public int Height { get { return mData.Metadata.GridHeight; } }
99
100 /// <summary>
101 /// Get the name of the tileset.
102 /// </summary>
103 public string Tileset { get { return mData.Metadata.Tileset; } }
104
105 /// <summary>
106 /// Get the current grid of open cells. On the grid, true means
107 /// the cell is open (i.e. an entity can occupy that cell), and false
108 /// means the cell is closed. Note that, just like Map.IsCellOpen,
109 /// only static scenery is considered; the grid cannot tell you
110 /// whether or not an entity is already occupying the cell.
111 /// </summary>
112 public bool[,] Grid { get { return mData.Grid; } }
113
114 /// <summary>
115 /// Get a list of the raw entity containers loaded with the map. If you
116 /// want to get the actual entity objects, use Map.GetEntities and
117 /// Map.GetAllEntities instead.
118 /// </summary>
119 public List<RawEntity> RawEntities { get { return mData.Entities; } }
120
121
122 /// <summary>
123 /// Get and set the coordinate of the grid cell that should be in
124 /// the center of the screen when the map is drawn. Setting this
125 /// will change the viewport of the map and will effect the return
126 /// values of Map.GetPointFromCoordinates and Map.GetRectangleFromCoordinates.
127 /// </summary>
128 public Vector2 CenterCell
129 {
130 get { return mView.CenterCell; }
131 set { mView.CenterCell = value; }
132 }
133
134 /// <summary>
135 /// Get and set the tilemap with its associated texture and tile
136 /// character to coordinate mappings. This effects what the map looks
137 /// like when it is drawn.
138 /// </summary>
139 public Tilemap Tilemap
140 {
141 get { return mData.Tilemap; }
142 set { mData.Tilemap = value; }
143 }
144
145 /// <summary>
146 /// Get and set the zoom of the map view. The default zoom is
147 /// Map.PixelsToUnitSquares.
148 /// </summary>
149 public float Zoom
150 {
151 get { return mView.Zoom; }
152 set { mView.Zoom = value; }
153 }
154
155 #endregion
156
157
158 #region Public Methods
159
160 /// <summary>
161 /// Construct a map with the provided map data.
162 /// </summary>
163 /// <param name="metadata">The metadata.</param>
164 /// <param name="grid">The grid.</param>
165 /// <param name="entities">The entities.</param>
166 public Map(Metadata metadata, char[,] grid, char defaultTile,
167 List<RawEntity> entities, Point[] playerPositions)
168 {
169 mData = new Model(metadata, grid, defaultTile, entities, playerPositions);
170 mView = new View(mData);
171 }
172
173
174 /// <summary>
175 /// Draw a representation of the map to the screen.
176 /// </summary>
177 /// <param name="spriteBatch">The jeewiz.</param>
178 public void Draw(SpriteBatch spriteBatch)
179 {
180 mView.Draw(spriteBatch);
181 }
182
183
184 /// <summary>
185 /// Get a point in screen-space from a coordinate in gridspace.
186 /// </summary>
187 /// <param name="x">X-coordinate.</param>
188 /// <param name="y">Y-coordinate.</param>
189 /// <returns>Transformed point.</returns>
190 public Point GetPointFromCoordinates(float x, float y)
191 {
192 return mView.GetPointFromCoordinates(x, y);
193 }
194
195 /// <summary>
196 /// Get a point in screen-space from a coordinate in gridspace.
197 /// </summary>
198 /// <param name="point">X,Y-coordinates.</param>
199 /// <returns>Transformed point.</returns>
200 public Point GetPointFromCoordinates(Vector2 point)
201 {
202 return mView.GetPointFromCoordinates(point.X, point.Y);
203 }
204
205 /// <summary>
206 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
207 /// </summary>
208 /// <param name="x">X-coordinate.</param>
209 /// <param name="y">Y-coordinate.</param>
210 /// <returns>Transformed rectangle.</returns>
211 public Rectangle GetRectangleFromCoordinates(float x, float y)
212 {
213 return mView.GetRectangleFromCoordinates(x, y);
214 }
215
216 /// <summary>
217 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
218 /// </summary>
219 /// <param name="point">X,Y-coordinates.</param>
220 /// <returns>Transformed rectangle.</returns>
221 public Rectangle GetRectangleFromCoordinates(Vector2 point)
222 {
223 return mView.GetRectangleFromCoordinates(point.X, point.Y);
224 }
225
226
227 /// <summary>
228 /// Determine whether or not a cell can be occupied by a game entity.
229 /// </summary>
230 /// <param name="x">X-coordinate.</param>
231 /// <param name="y">Y-coordinate.</param>
232 /// <returns>True if cell can be occupied, false otherwise.</returns>
233 public bool IsCellOpen(int x, int y)
234 {
235 return mData.IsCellOpen(x, y);
236 }
237
238 /// <summary>
239 /// created by Brady for AI precalculations
240 /// </summary>
241 /// <param name="x">X-coordinate.</param>
242 /// <param name="y">Y-coordinate.</param>
243 public bool IsWall(int x, int y)
244 {
245 return mData.IsWall(x, y);
246 }
247
248 /// <summary>
249 /// Determine whether or not a cell can be occupied by a game entity.
250 /// </summary>
251 /// <param name="point">X,Y-coordinates.</param>
252 /// <returns>True if cell can be occupied, false otherwise.</returns>
253 public bool IsCellOpen(Point point)
254 {
255 return mData.IsCellOpen(point.X, point.Y);
256 }
257
258
259 /// <summary>
260 /// Get the starting position of a player.
261 /// </summary>
262 /// <param name="playerNumber">The number of the player (i.e. 1-4).
263 /// This number must be a valid player number.</param>
264 /// <returns>The starting position of the player.</returns>
265 public Point GetStartingPositionForPlayer(int playerNumber)
266 {
267 Debug.Assert(1 <= playerNumber && playerNumber <= NumPlayers.Max());
268 return mData.PlayerPositions[playerNumber];
269 }
270
271
272 /// <summary>
273 /// Get all the entities loaded from the map file. Exceptions could be
274 /// thrown if there are entities without associated classes.
275 /// </summary>
276 /// <param name="game">The game reference to be passed to entities.</param>
277 /// <returns>List of entity objects loaded.</returns>
278 public List<IEntity> GetAllEntities(Game game)
279 {
280 return mData.GetAllEntities(game);
281 }
282
283 /// <summary>
284 /// Get the entities of a certain type loaded from the map file. Exceptions
285 /// could be thrown if there are entities without associated classes.
286 /// </summary>
287 /// <param name="game">The game reference to be passed to entities.</param>
288 /// <typeparam name="T">Type of the entity you want a list of.</typeparam>
289 /// <returns>List of entity objects loaded.</returns>
290 public List<T> GetEntities<T>(Game game)
291 {
292 return mData.GetEntities<T>(game);
293 }
294
295
296 /// <summary>
297 /// Set the tile of a cell.
298 /// </summary>
299 /// <param name="x">X-coordinate.</param>
300 /// <param name="y">Y-coordinate.</param>
301 /// <param name="tile">The character representing the tile.</param>
302 public void SetCell(int x, int y, char tile)
303 {
304 mData.SetCell(x, y, tile);
305 }
306
307 /// <summary>
308 /// Set the tile of a cell.
309 /// </summary>
310 /// <param name="point">X,Y-coordinates.</param>
311 /// <param name="tile">The character representing the tile.</param>
312 public void SetCell(Point point, char tile)
313 {
314 mData.SetCell(point.X, point.Y, tile);
315 }
316
317
318 /// <summary>
319 /// Clear a cell to the default tile.
320 /// </summary>
321 /// <param name="x">X-coordinate.</param>
322 /// <param name="y">Y-coordinate.</param>
323 public void ClearCell(int x, int y)
324 {
325 mData.ClearCell(x, y);
326 }
327
328 /// <summary>
329 /// Clear a cell to the default tile.
330 /// </summary>
331 /// <param name="point">X,Y-coordinates.</param>
332 public void ClearCell(Point point)
333 {
334 mData.ClearCell(point.X, point.Y);
335 }
336
337
338 /// <summary>
339 /// Reset the map to the state it was at right after loading.
340 /// </summary>
341 public void Reset()
342 {
343 mData.Reset();
344 mView.Reset();
345 }
346
347 #endregion
348
349
350 #region Private Types
351
352 class Model
353 {
354 public Metadata Metadata { get { return mMetadata; } }
355 public List<RawEntity> Entities { get { return mEntities; } }
356 public Point[] PlayerPositions { get { return mPlayerPositions; } }
357 public bool[,] Grid { get { return mBooleanGrid; } }
358 public Tilemap Tilemap;
359
360
361 public Model(Metadata metadata, char[,] grid, char defaultTile,
362 List<RawEntity> entities, Point[] playerPositions)
363 {
364 Debug.Assert(metadata != null);
365 Debug.Assert(grid != null);
366 Debug.Assert(entities != null);
367 Debug.Assert(metadata.GridWidth * metadata.GridHeight == grid.Length);
368
369 mMetadata = metadata;
370 mCleanGrid = grid;
371 mDefaultTile = defaultTile;
372 mEntities = entities;
373 mPlayerPositions = playerPositions;
374
375 Reset();
376
377 #if DEBUG
378 Console.WriteLine("Loaded map {0} of type {1} written by {2}.",
379 metadata.Name,
380 metadata.Type,
381 metadata.Author);
382 #endif
383 }
384
385
386 public void Reset()
387 {
388 mGrid = (char[,])mCleanGrid.Clone();
389
390 mBooleanGrid = new bool[mMetadata.GridWidth, mMetadata.GridHeight];
391 for (int x = 0; x < mMetadata.GridWidth; x++)
392 {
393 for (int y = 0; y < mMetadata.GridHeight; y++)
394 {
395 mBooleanGrid[x, y] = IsCellOpen(x, y);
396 }
397 }
398 }
399
400
401 public bool IsCellOpen(int x, int y)
402 {
403 if (!IsOnMap(x, y)) return false;
404 return (Tilemap.GetTileFlags(mGrid[x, y]) & TileFlags.Open) == TileFlags.Open;
405 }
406
407 //created by Brady for AI precalculations
408 public bool IsWall(int x, int y)
409 {
410 if (!IsOnMap(x, y)) return false;
411 return (Tilemap.GetTileFlags(mGrid[x, y]) & TileFlags.Wall) == TileFlags.Wall;
412 }
413
414 public void SetCell(int x, int y, char tile)
415 {
416 if (IsOnMap(x, y))
417 {
418 mGrid[x, y] = tile;
419 mBooleanGrid[x, y] = IsCellOpen(x, y);
420 }
421 }
422
423 public char GetCell(int x, int y)
424 {
425 if (IsOnMap(x, y)) return mGrid[x, y];
426 return mDefaultTile;
427 }
428
429 public void ClearCell(int x, int y)
430 {
431 SetCell(x, y, mDefaultTile);
432 }
433
434 public bool IsOnMap(int x, int y)
435 {
436 return 0 <= x && x < Metadata.GridWidth && 0 <= y && y < Metadata.GridHeight;
437 }
438
439
440 public List<IEntity> GetAllEntities(Game game)
441 {
442 List<IEntity> list = new List<IEntity>();
443
444 foreach (RawEntity raw in mEntities)
445 {
446 if (raw.Attributes.ContainsKey("type"))
447 {
448 string typename = raw.Attributes["type"];
449
450 object[] args = new object[4];
451 args[0] = raw.Id;
452 args[1] = raw.Position;
453 args[2] = raw.Attributes;
454 args[3] = game;
455
456 try
457 {
458 IEntity entity = (IEntity)Activator.CreateInstance(System.Type.GetType("CarFire." + typename), args);
459 if (entity != null)
460 {
461 entity.LoadContent(game.ContentManager);
462 list.Add(entity);
463 }
464 else throw new Exception();
465 }
466 #pragma warning disable 0168
467 catch (System.Exception ex)
468 #pragma warning restore 0168
469 {
470 throw new Exception("Entity of type " + typename + " not loaded because an entity class can't be found.");
471 }
472 }
473 else
474 {
475 Console.WriteLine("Ignoring entity with identifier " + raw.Id + " since it has no type key.");
476 }
477 }
478
479 return list;
480 }
481
482 public List<T> GetEntities<T>(Game game)
483 {
484 System.Type type = typeof(T);
485 List<T> list = new List<T>();
486
487 string typename = typeof(T).Name;
488 foreach (RawEntity raw in mEntities)
489 {
490 if (raw.Attributes.ContainsKey("type") && typename == raw.Attributes["type"])
491 {
492 object[] args = new object[4];
493 args[0] = raw.Id;
494 args[1] = raw.Position;
495 args[2] = raw.Attributes;
496 args[3] = game;
497
498 T entity = (T)Activator.CreateInstance(type, args);
499 if (entity != null)
500 {
501 ((IEntity)entity).LoadContent(game.ContentManager);
502 list.Add(entity);
503 }
504 else throw new Exception("Entity of type " + typename + " not loaded because an entity class can't be found.");
505 }
506 }
507
508 return list;
509 }
510
511
512 Metadata mMetadata;
513 char[,] mGrid;
514 char[,] mCleanGrid;
515 bool[,] mBooleanGrid;
516 char mDefaultTile;
517 List<RawEntity> mEntities;
518 Point[] mPlayerPositions;
519 }
520
521 class View
522 {
523 public Vector2 CenterCell;
524 public float Zoom;
525
526
527 public View(Model data)
528 {
529 Debug.Assert(data != null);
530 mData = data;
531
532 Reset();
533 }
534
535
536 public void Reset()
537 {
538 CenterCell = Vector2.Zero;
539 Zoom = PixelsToUnitSquares;
540 }
541
542
543 public void Draw(SpriteBatch spriteBatch)
544 {
545 if (mData.Tilemap == null) throw new Exception("Cannot draw map without first setting the tilemap.");
546 mViewport = spriteBatch.GraphicsDevice.Viewport;
547
548 for (int y = 0; y < mData.Metadata.GridHeight; y++)
549 {
550 for (int x = 0; x < mData.Metadata.GridWidth; x++)
551 {
552 mData.Tilemap.Draw(spriteBatch, mData.GetCell(x, y), GetRectangleFromCoordinates(x, y));
553 }
554 }
555 }
556
557
558 public Point GetPointFromCoordinates(float x, float y)
559 {
560 Matrix transform = GetTransformation(CenterCell);
561 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
562
563 return new Point((int)point.X, (int)point.Y);
564 }
565
566 public Rectangle GetRectangleFromCoordinates(float x, float y)
567 {
568 Matrix transform = GetTransformation(CenterCell);
569 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
570
571 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));
572 }
573
574
575
576 Matrix GetTransformation(Vector2 center)
577 {
578 float halfRatio = Zoom * 0.5f;
579 Matrix transform = Matrix.CreateTranslation(-center.X, -center.Y, 0.0f);
580 transform *= Matrix.CreateScale(Zoom);
581 transform *= Matrix.CreateTranslation(mViewport.Width * 0.5f - halfRatio,
582 mViewport.Height * 0.5f - halfRatio, 0.0f);
583
584 Vector2 topLeft = Vector2.Transform(new Vector2(0.0f, 0.0f), transform);
585 topLeft.X = Math.Max(mViewport.X, topLeft.X);
586 topLeft.Y = Math.Max(mViewport.Y, topLeft.Y);
587 transform *= Matrix.CreateTranslation(-topLeft.X, -topLeft.Y, 0.0f);
588
589 Vector2 bottomRight = Vector2.Transform(new Vector2((float)mData.Metadata.GridWidth,
590 (float)mData.Metadata.GridHeight), transform);
591 float right = mViewport.X + mViewport.Width;
592 float bottom = mViewport.Y + mViewport.Height;
593 bottomRight.X = Math.Min(right, bottomRight.X) - right;
594 bottomRight.Y = Math.Min(bottom, bottomRight.Y) - bottom;
595 transform *= Matrix.CreateTranslation(-bottomRight.X, -bottomRight.Y, 0.0f);
596
597 return transform;
598 }
599
600
601 Model mData;
602 Viewport mViewport;
603 }
604
605 #endregion
606
607
608 #region Private Variables
609
610 Model mData;
611 View mView;
612
613 #endregion
614 }
615 }
This page took 0.057076 seconds and 5 git commands to generate.