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