]> Dogcows Code - chaz/carfire/blob - CarFire/CarFire/CarFire/Map.cs
New map methods Map.SetCell and Map.ClearCell to modify the tiles of the map. These...
[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 // DEBUG: Tilesets not implemented at all.
23 public static Texture2D DefaultTile;
24
25 #region Public Exceptions
26
27 /// <summary>
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
30 /// and order.
31 /// </summary>
32 public class RuntimeException : System.ApplicationException
33 {
34 public RuntimeException() { }
35
36 public RuntimeException(string message) :
37 base(message) { }
38
39 public RuntimeException(string message, System.Exception inner) :
40 base(message, inner) { }
41
42 protected RuntimeException(SerializationInfo info, StreamingContext context) :
43 base(info, context) { }
44 }
45
46 #endregion
47
48
49 #region Public Constants
50
51 public const float PixelsToUnitSquares = 60.0f;
52
53 #endregion
54
55
56 #region Public Types
57
58 /// <summary>
59 /// The type of a map helps determine how the map is intended to be used.
60 /// </summary>
61 public enum Mode
62 {
63 None,
64 Campaign,
65 Battle
66 }
67
68 /// <summary>
69 /// The container class for map metadata.
70 /// </summary>
71 public class Metadata
72 {
73 public string Name;
74 public Mode Type;
75 public string Author;
76 public HashSet<int> NumPlayers = new HashSet<int>();
77 public string Tileset;
78 public int GridWidth;
79 public int GridHeight;
80 }
81
82 /// <summary>
83 /// The container class for information about an entity defined in the map.
84 /// </summary>
85 public class RawEntity
86 {
87 public char Id;
88 public Point Position;
89 public Dictionary<string, string> Attributes = new Dictionary<string, string>();
90 }
91
92 #endregion
93
94
95 #region Public Attributes
96
97 /// <summary>
98 /// Get the name of the map.
99 /// </summary>
100 public string Name { get { return mData.Metadata.Name; } }
101
102 /// <summary>
103 /// Get the type of the map.
104 /// </summary>
105 public Mode Type { get { return mData.Metadata.Type; } }
106
107 /// <summary>
108 /// Get the author of the map.
109 /// </summary>
110 public string Author { get { return mData.Metadata.Author; } }
111
112 /// <summary>
113 /// Get a set of integers containing each allowable number of players.
114 /// </summary>
115 public HashSet<int> NumPlayers { get { return mData.Metadata.NumPlayers; } }
116
117 /// <summary>
118 /// Get the width of the map, in grid units.
119 /// </summary>
120 public int Width { get { return mData.Metadata.GridWidth; } }
121
122 /// <summary>
123 /// Get the height of the map, in grid units.
124 /// </summary>
125 public int Height { get { return mData.Metadata.GridHeight; } }
126
127 // TODO: This should return whatever object we end up using for tilesets.
128 public string Tileset { get { return mData.Metadata.Tileset; } }
129
130 /// <summary>
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.
136 /// </summary>
137 public bool[,] Grid { get { return mData.Grid; } }
138
139 /// <summary>
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.
143 /// </summary>
144 public List<RawEntity> RawEntities { get { return mData.Entities; } }
145
146
147 /// <summary>
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.
152 /// </summary>
153 public Vector2 CenterCell
154 {
155 get { return mView.CenterCell; }
156 set { mView.CenterCell = 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 Modal(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 /// Determine whether or not a cell can be occupied by a game entity.
244 /// </summary>
245 /// <param name="point">X,Y-coordinates.</param>
246 /// <returns>True if cell can be occupied, false otherwise.</returns>
247 public bool IsCellOpen(Point point)
248 {
249 return mData.IsCellOpen(point.X, point.Y);
250 }
251
252
253 /// <summary>
254 /// Get the starting position of a player.
255 /// </summary>
256 /// <param name="playerNumber">The number of the player (i.e. 1-4).
257 /// This number must be a valid player number.</param>
258 /// <returns>The starting position of the player.</returns>
259 public Point GetStartingPositionForPlayer(int playerNumber)
260 {
261 Debug.Assert(1 <= playerNumber && playerNumber <= NumPlayers.Max());
262 return mData.PlayerPositions[playerNumber];
263 }
264
265
266 /// <summary>
267 /// Get all the entities loaded from the map file. Exceptions could be
268 /// thrown if there are entities without associated classes.
269 /// </summary>
270 /// <returns>List of entity objects loaded.</returns>
271 public List<object> GetAllEntities()
272 {
273 return mData.GetAllEntities();
274 }
275
276 /// <summary>
277 /// Get the entities of a certain type loaded from the map file. Exceptions
278 /// could be thrown if there are entities without associated classes.
279 /// </summary>
280 /// <typeparam name="T">Type of the entity you want a list of.</typeparam>
281 /// <returns>List of entity objects loaded.</returns>
282 public List<T> GetEntities<T>()
283 {
284 return mData.GetEntities<T>();
285 }
286
287
288 /// <summary>
289 /// Set the tile of a cell.
290 /// </summary>
291 /// <param name="x">X-coordinate.</param>
292 /// <param name="y">Y-coordinate.</param>
293 /// <param name="tile">The character representing the tile.</param>
294 public void SetCell(int x, int y, char tile)
295 {
296 mData.SetCell(x, y, tile);
297 }
298
299 /// <summary>
300 /// Set the tile of a cell.
301 /// </summary>
302 /// <param name="point">X,Y-coordinates.</param>
303 /// <param name="tile">The character representing the tile.</param>
304 public void SetCell(Point point, char tile)
305 {
306 mData.SetCell(point.X, point.Y, tile);
307 }
308
309
310 /// <summary>
311 /// Clear a cell to the default tile.
312 /// </summary>
313 /// <param name="x">X-coordinate.</param>
314 /// <param name="y">Y-coordinate.</param>
315 public void ClearCell(int x, int y)
316 {
317 mData.ClearCell(x, y);
318 }
319
320 /// <summary>
321 /// Clear a cell to the default tile.
322 /// </summary>
323 /// <param name="point">X,Y-coordinates.</param>
324 public void ClearCell(Point point)
325 {
326 mData.ClearCell(point.X, point.Y);
327 }
328
329 #endregion
330
331
332 #region Private Types
333
334 class Modal
335 {
336 Metadata mMetadata;
337 char[,] mGrid;
338 char mDefaultTile;
339 List<RawEntity> mEntities;
340 Point[] mPlayerPositions;
341 bool[,] mBooleanGrid;
342
343 public Modal(Metadata metadata, char[,] grid, char defaultTile,
344 List<RawEntity> entities, Point[] playerPositions)
345 {
346 Debug.Assert(metadata != null);
347 Debug.Assert(grid != null);
348 Debug.Assert(entities != null);
349 Debug.Assert(metadata.GridWidth * metadata.GridHeight == grid.Length);
350
351 mMetadata = metadata;
352 mGrid = grid;
353 mDefaultTile = defaultTile;
354 mEntities = entities;
355 mPlayerPositions = playerPositions;
356
357 mBooleanGrid = new bool[mMetadata.GridWidth, mMetadata.GridHeight];
358 for (int x = 0; x < mMetadata.GridWidth; x++)
359 {
360 for (int y = 0; y < mMetadata.GridHeight; y++)
361 {
362 mBooleanGrid[x, y] = IsCellOpen(x, y);
363 }
364 }
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 Metadata Metadata { get { return mMetadata; } }
376 public List<RawEntity> Entities { get { return mEntities; } }
377 public Point[] PlayerPositions { get { return mPlayerPositions; } }
378 public bool[,] Grid { get { return mBooleanGrid; } }
379
380
381 public bool IsCellOpen(int x, int y)
382 {
383 // TODO: Still need to define characters for types of scenery.
384 return mGrid[x, y] == ' ';
385 }
386
387 public void SetCell(int x, int y, char tile)
388 {
389 mGrid[x, y] = tile;
390 mBooleanGrid[x, y] = IsCellOpen(x, y);
391 }
392
393 public void ClearCell(int x, int y)
394 {
395 SetCell(x, y, mDefaultTile);
396 }
397
398
399 public List<object> GetAllEntities()
400 {
401 List<object> list = new List<object>();
402
403 foreach (RawEntity raw in mEntities)
404 {
405 if (raw.Attributes.ContainsKey("type"))
406 {
407 string typename = raw.Attributes["type"];
408
409 object[] args = new object[3];
410 args[0] = raw.Id;
411 args[1] = raw.Position;
412 args[2] = raw.Attributes;
413
414 try
415 {
416
417 object entity = Activator.CreateInstance(System.Type.GetType("CarFire." + typename), args);
418 if (entity != null) list.Add(entity);
419 else throw new RuntimeException();
420 }
421 #pragma warning disable 0168
422 catch (System.Exception ex)
423 #pragma warning restore 0168
424 {
425 throw new RuntimeException("Entity of type " + typename + " not loaded because an entity class can't be found.");
426 }
427 }
428 else
429 {
430 Console.WriteLine("Ignoring entity with identifier " + raw.Id + " since it has no type key.");
431 }
432 }
433
434 return list;
435 }
436
437 public List<T> GetEntities<T>()
438 {
439 System.Type type = typeof(T);
440 List<T> list = new List<T>();
441
442 string typename = typeof(T).Name;
443 foreach (RawEntity raw in mEntities)
444 {
445 if (raw.Attributes.ContainsKey("type") && typename == raw.Attributes["type"])
446 {
447 object[] args = new object[3];
448 args[0] = raw.Id;
449 args[1] = raw.Position;
450 args[2] = raw.Attributes;
451
452 T entity = (T)Activator.CreateInstance(type, args);
453 if (entity != null) list.Add(entity);
454 else throw new RuntimeException("Entity of type " + typename + " not loaded because an entity class can't be found.");
455 }
456 }
457
458 return list;
459 }
460 }
461
462 class View
463 {
464 Modal mData;
465
466 public Vector2 CenterCell;
467 Viewport mViewport;
468
469
470 public View(Modal data)
471 {
472 Debug.Assert(data != null);
473 mData = data;
474 }
475
476 public void Draw(SpriteBatch spriteBatch)
477 {
478 mViewport = spriteBatch.GraphicsDevice.Viewport;
479
480 // TODO: There is no culling yet, but it runs so fast that it probably won't ever need it.
481 for (int y = 0; y < mData.Metadata.GridHeight; y++)
482 {
483 for (int x = 0; x < mData.Metadata.GridWidth; x++)
484 {
485 if (mData.IsCellOpen(x, y))
486 {
487 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.White);
488 }
489 else
490 {
491 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.DarkBlue);
492 }
493 }
494 }
495 }
496
497 /// <summary>
498 /// Get a matrix to transform a point from grid-space to screen coordinates. This
499 /// method uses the viewport to bound the edges of the map such that the camera
500 /// will not show anything outside of the grid.
501 /// </summary>
502 /// <param name="center">The point to put in the center.</param>
503 /// <returns>The transformation matrix.</returns>
504 Matrix GetTransformation(Vector2 center)
505 {
506 float halfRatio = PixelsToUnitSquares * 0.5f;
507 Matrix transform = Matrix.CreateTranslation(-center.X, -center.Y, 0.0f);
508 transform *= Matrix.CreateScale(PixelsToUnitSquares);
509 transform *= Matrix.CreateTranslation(mViewport.Width * 0.5f - halfRatio,
510 mViewport.Height * 0.5f - halfRatio, 0.0f);
511
512 Vector2 topLeft = Vector2.Transform(new Vector2(0.0f, 0.0f), transform);
513 topLeft.X = Math.Max(mViewport.X, topLeft.X);
514 topLeft.Y = Math.Max(mViewport.Y, topLeft.Y);
515 transform *= Matrix.CreateTranslation(-topLeft.X, -topLeft.Y, 0.0f);
516
517 Vector2 bottomRight = Vector2.Transform(new Vector2((float)mData.Metadata.GridWidth,
518 (float)mData.Metadata.GridHeight), transform);
519 float right = mViewport.X + mViewport.Width;
520 float bottom = mViewport.Y + mViewport.Height;
521 bottomRight.X = Math.Min(right, bottomRight.X) - right;
522 bottomRight.Y = Math.Min(bottom, bottomRight.Y) - bottom;
523 transform *= Matrix.CreateTranslation(-bottomRight.X, -bottomRight.Y, 0.0f);
524
525 return transform;
526 }
527
528
529 public Point GetPointFromCoordinates(float x, float y)
530 {
531 Matrix transform = GetTransformation(CenterCell);
532 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
533
534 return new Point((int)point.X, (int)point.Y);
535 }
536
537 public Rectangle GetRectangleFromCoordinates(float x, float y)
538 {
539 Matrix transform = GetTransformation(CenterCell);
540 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
541
542 return new Rectangle((int)point.X, (int)point.Y, (int)PixelsToUnitSquares, (int)PixelsToUnitSquares);
543 }
544 }
545
546 #endregion
547
548
549 #region Private Variables
550
551 Modal mData;
552 View mView;
553
554 #endregion
555 }
556 }
This page took 0.06663 seconds and 4 git commands to generate.