]> Dogcows Code - chaz/carfire/blob - CarFire/CarFire/CarFire/Map.cs
Implemented map tiles; started new Key entity; added missing variables to Melee.cs...
[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 mView.Tilemap; }
142 set { mView.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 /// Determine whether or not a cell can be occupied by a game entity.
240 /// </summary>
241 /// <param name="point">X,Y-coordinates.</param>
242 /// <returns>True if cell can be occupied, false otherwise.</returns>
243 public bool IsCellOpen(Point point)
244 {
245 return mData.IsCellOpen(point.X, point.Y);
246 }
247
248
249 /// <summary>
250 /// Get the starting position of a player.
251 /// </summary>
252 /// <param name="playerNumber">The number of the player (i.e. 1-4).
253 /// This number must be a valid player number.</param>
254 /// <returns>The starting position of the player.</returns>
255 public Point GetStartingPositionForPlayer(int playerNumber)
256 {
257 Debug.Assert(1 <= playerNumber && playerNumber <= NumPlayers.Max());
258 return mData.PlayerPositions[playerNumber];
259 }
260
261
262 /// <summary>
263 /// Get all the entities loaded from the map file. Exceptions could be
264 /// thrown if there are entities without associated classes.
265 /// </summary>
266 /// <param name="game">The game reference to be passed to entities.</param>
267 /// <returns>List of entity objects loaded.</returns>
268 public List<IEntity> GetAllEntities(Game game)
269 {
270 return mData.GetAllEntities(game);
271 }
272
273 /// <summary>
274 /// Get the entities of a certain type loaded from the map file. Exceptions
275 /// could be thrown if there are entities without associated classes.
276 /// </summary>
277 /// <param name="game">The game reference to be passed to entities.</param>
278 /// <typeparam name="T">Type of the entity you want a list of.</typeparam>
279 /// <returns>List of entity objects loaded.</returns>
280 public List<T> GetEntities<T>(Game game)
281 {
282 return mData.GetEntities<T>(game);
283 }
284
285
286 /// <summary>
287 /// Set the tile of a cell.
288 /// </summary>
289 /// <param name="x">X-coordinate.</param>
290 /// <param name="y">Y-coordinate.</param>
291 /// <param name="tile">The character representing the tile.</param>
292 public void SetCell(int x, int y, char tile)
293 {
294 mData.SetCell(x, y, tile);
295 }
296
297 /// <summary>
298 /// Set the tile of a cell.
299 /// </summary>
300 /// <param name="point">X,Y-coordinates.</param>
301 /// <param name="tile">The character representing the tile.</param>
302 public void SetCell(Point point, char tile)
303 {
304 mData.SetCell(point.X, point.Y, tile);
305 }
306
307
308 /// <summary>
309 /// Clear a cell to the default tile.
310 /// </summary>
311 /// <param name="x">X-coordinate.</param>
312 /// <param name="y">Y-coordinate.</param>
313 public void ClearCell(int x, int y)
314 {
315 mData.ClearCell(x, y);
316 }
317
318 /// <summary>
319 /// Clear a cell to the default tile.
320 /// </summary>
321 /// <param name="point">X,Y-coordinates.</param>
322 public void ClearCell(Point point)
323 {
324 mData.ClearCell(point.X, point.Y);
325 }
326
327
328 /// <summary>
329 /// Reset the map to the state it was at right after loading.
330 /// </summary>
331 public void Reset()
332 {
333 mData.Reset();
334 mView.Reset();
335 }
336
337 #endregion
338
339
340 #region Private Types
341
342 class Model
343 {
344 public Metadata Metadata { get { return mMetadata; } }
345 public List<RawEntity> Entities { get { return mEntities; } }
346 public Point[] PlayerPositions { get { return mPlayerPositions; } }
347 public bool[,] Grid { get { return mBooleanGrid; } }
348
349
350 public Model(Metadata metadata, char[,] grid, char defaultTile,
351 List<RawEntity> entities, Point[] playerPositions)
352 {
353 Debug.Assert(metadata != null);
354 Debug.Assert(grid != null);
355 Debug.Assert(entities != null);
356 Debug.Assert(metadata.GridWidth * metadata.GridHeight == grid.Length);
357
358 mMetadata = metadata;
359 mCleanGrid = grid;
360 mDefaultTile = defaultTile;
361 mEntities = entities;
362 mPlayerPositions = playerPositions;
363
364 Reset();
365
366 #if DEBUG
367 Console.WriteLine("Loaded map {0} of type {1} written by {2}.",
368 metadata.Name,
369 metadata.Type,
370 metadata.Author);
371 #endif
372 }
373
374
375 public void Reset()
376 {
377 mGrid = (char[,])mCleanGrid.Clone();
378
379 mBooleanGrid = new bool[mMetadata.GridWidth, mMetadata.GridHeight];
380 for (int x = 0; x < mMetadata.GridWidth; x++)
381 {
382 for (int y = 0; y < mMetadata.GridHeight; y++)
383 {
384 mBooleanGrid[x, y] = IsCellOpen(x, y);
385 }
386 }
387 }
388
389
390 public bool IsCellOpen(int x, int y)
391 {
392 // TODO: Still need to define characters for types of scenery.
393 if (IsOnMap(x, y)) return mGrid[x, y] == ' ';
394 return false;
395 }
396
397 public void SetCell(int x, int y, char tile)
398 {
399 if (IsOnMap(x, y))
400 {
401 mGrid[x, y] = tile;
402 mBooleanGrid[x, y] = IsCellOpen(x, y);
403 }
404 }
405
406 public char GetCell(int x, int y)
407 {
408 if (IsOnMap(x, y)) return mGrid[x, y];
409 return mDefaultTile;
410 }
411
412 public void ClearCell(int x, int y)
413 {
414 SetCell(x, y, mDefaultTile);
415 }
416
417 public bool IsOnMap(int x, int y)
418 {
419 return 0 <= x && x < Metadata.GridWidth && 0 <= y && y < Metadata.GridHeight;
420 }
421
422
423 public List<IEntity> GetAllEntities(Game game)
424 {
425 List<IEntity> list = new List<IEntity>();
426
427 foreach (RawEntity raw in mEntities)
428 {
429 if (raw.Attributes.ContainsKey("type"))
430 {
431 string typename = raw.Attributes["type"];
432
433 object[] args = new object[4];
434 args[0] = raw.Id;
435 args[1] = raw.Position;
436 args[2] = raw.Attributes;
437 args[3] = game;
438
439 try
440 {
441 IEntity entity = (IEntity)Activator.CreateInstance(System.Type.GetType("CarFire." + typename), args);
442 if (entity != null)
443 {
444 entity.LoadContent(game.ContentManager);
445 list.Add(entity);
446 }
447 else throw new Exception();
448 }
449 #pragma warning disable 0168
450 catch (System.Exception ex)
451 #pragma warning restore 0168
452 {
453 throw new Exception("Entity of type " + typename + " not loaded because an entity class can't be found.");
454 }
455 }
456 else
457 {
458 Console.WriteLine("Ignoring entity with identifier " + raw.Id + " since it has no type key.");
459 }
460 }
461
462 return list;
463 }
464
465 public List<T> GetEntities<T>(Game game)
466 {
467 System.Type type = typeof(T);
468 List<T> list = new List<T>();
469
470 string typename = typeof(T).Name;
471 foreach (RawEntity raw in mEntities)
472 {
473 if (raw.Attributes.ContainsKey("type") && typename == raw.Attributes["type"])
474 {
475 object[] args = new object[4];
476 args[0] = raw.Id;
477 args[1] = raw.Position;
478 args[2] = raw.Attributes;
479 args[3] = game;
480
481 T entity = (T)Activator.CreateInstance(type, args);
482 if (entity != null)
483 {
484 ((IEntity)entity).LoadContent(game.ContentManager);
485 list.Add(entity);
486 }
487 else throw new Exception("Entity of type " + typename + " not loaded because an entity class can't be found.");
488 }
489 }
490
491 return list;
492 }
493
494
495 Metadata mMetadata;
496 char[,] mGrid;
497 char[,] mCleanGrid;
498 bool[,] mBooleanGrid;
499 char mDefaultTile;
500 List<RawEntity> mEntities;
501 Point[] mPlayerPositions;
502 }
503
504 class View
505 {
506 public Vector2 CenterCell;
507 public Tilemap Tilemap;
508 public float Zoom;
509
510
511 public View(Model data)
512 {
513 Debug.Assert(data != null);
514 mData = data;
515
516 Reset();
517 }
518
519
520 public void Reset()
521 {
522 CenterCell = Vector2.Zero;
523 Zoom = PixelsToUnitSquares;
524 }
525
526
527 public void Draw(SpriteBatch spriteBatch)
528 {
529 if (Tilemap == null) throw new Exception("Cannot draw map without first setting the tilemap.");
530 mViewport = spriteBatch.GraphicsDevice.Viewport;
531
532 for (int y = 0; y < mData.Metadata.GridHeight; y++)
533 {
534 for (int x = 0; x < mData.Metadata.GridWidth; x++)
535 {
536 Tilemap.Draw(spriteBatch, mData.GetCell(x, y), GetRectangleFromCoordinates(x, y));
537 }
538 }
539 }
540
541
542 public Point GetPointFromCoordinates(float x, float y)
543 {
544 Matrix transform = GetTransformation(CenterCell);
545 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
546
547 return new Point((int)point.X, (int)point.Y);
548 }
549
550 public Rectangle GetRectangleFromCoordinates(float x, float y)
551 {
552 Matrix transform = GetTransformation(CenterCell);
553 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
554
555 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));
556 }
557
558
559
560 Matrix GetTransformation(Vector2 center)
561 {
562 float halfRatio = Zoom * 0.5f;
563 Matrix transform = Matrix.CreateTranslation(-center.X, -center.Y, 0.0f);
564 transform *= Matrix.CreateScale(Zoom);
565 transform *= Matrix.CreateTranslation(mViewport.Width * 0.5f - halfRatio,
566 mViewport.Height * 0.5f - halfRatio, 0.0f);
567
568 Vector2 topLeft = Vector2.Transform(new Vector2(0.0f, 0.0f), transform);
569 topLeft.X = Math.Max(mViewport.X, topLeft.X);
570 topLeft.Y = Math.Max(mViewport.Y, topLeft.Y);
571 transform *= Matrix.CreateTranslation(-topLeft.X, -topLeft.Y, 0.0f);
572
573 Vector2 bottomRight = Vector2.Transform(new Vector2((float)mData.Metadata.GridWidth,
574 (float)mData.Metadata.GridHeight), transform);
575 float right = mViewport.X + mViewport.Width;
576 float bottom = mViewport.Y + mViewport.Height;
577 bottomRight.X = Math.Min(right, bottomRight.X) - right;
578 bottomRight.Y = Math.Min(bottom, bottomRight.Y) - bottom;
579 transform *= Matrix.CreateTranslation(-bottomRight.X, -bottomRight.Y, 0.0f);
580
581 return transform;
582 }
583
584
585 Model mData;
586 Viewport mViewport;
587 }
588
589 #endregion
590
591
592 #region Private Variables
593
594 Model mData;
595 View mView;
596
597 #endregion
598 }
599 }
This page took 0.064331 seconds and 5 git commands to generate.