Level.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // Level.cs
  4. //
  5. // Microsoft XNA Community Game Platform
  6. // Copyright (C) Microsoft Corporation. All rights reserved.
  7. //-----------------------------------------------------------------------------
  8. #endregion
  9. using System;
  10. using System.Collections.Generic;
  11. using Microsoft.Xna.Framework;
  12. using Microsoft.Xna.Framework.Content;
  13. using Microsoft.Xna.Framework.Graphics;
  14. using Microsoft.Xna.Framework.Audio;
  15. using System.IO;
  16. using Microsoft.Xna.Framework.Input;
  17. namespace Platformer2D
  18. {
  19. /// <summary>
  20. /// A uniform grid of tiles with collections of gems and enemies.
  21. /// The level owns the player and controls the game's win and lose
  22. /// conditions as well as scoring.
  23. /// </summary>
  24. class Level : IDisposable
  25. {
  26. // Physical structure of the level.
  27. private Tile[,] tiles;
  28. private Texture2D[] layers;
  29. // The layer which entities are drawn on top of.
  30. private const int EntityLayer = 2;
  31. // Entities in the level.
  32. public Player Player
  33. {
  34. get { return player; }
  35. }
  36. Player player;
  37. private List<Gem> gems = new List<Gem>();
  38. private List<Enemy> enemies = new List<Enemy>();
  39. // Key locations in the level.
  40. private Vector2 start;
  41. private Point exit = InvalidPosition;
  42. private static readonly Point InvalidPosition = new Point(-1, -1);
  43. // Level game state.
  44. private Random random = new Random(354668); // Arbitrary, but constant seed
  45. public int Score
  46. {
  47. get { return score; }
  48. }
  49. int score;
  50. public bool ReachedExit
  51. {
  52. get { return reachedExit; }
  53. }
  54. bool reachedExit;
  55. public TimeSpan TimeRemaining
  56. {
  57. get { return timeRemaining; }
  58. }
  59. TimeSpan timeRemaining;
  60. private const int PointsPerSecond = 5;
  61. // Level content.
  62. public ContentManager Content
  63. {
  64. get { return content; }
  65. }
  66. ContentManager content;
  67. private SoundEffect exitReachedSound;
  68. #region Loading
  69. /// <summary>
  70. /// Constructs a new level.
  71. /// </summary>
  72. /// <param name="serviceProvider">
  73. /// The service provider that will be used to construct a ContentManager.
  74. /// </param>
  75. /// <param name="fileStream">
  76. /// A stream containing the tile data.
  77. /// </param>
  78. public Level(IServiceProvider serviceProvider, Stream fileStream, int levelIndex)
  79. {
  80. // Create a new content manager to load content used just by this level.
  81. content = new ContentManager(serviceProvider, "Content");
  82. timeRemaining = TimeSpan.FromMinutes(2.0);
  83. LoadTiles(fileStream);
  84. // Load background layer textures. For now, all levels must
  85. // use the same backgrounds and only use the left-most part of them.
  86. layers = new Texture2D[3];
  87. for (int i = 0; i < layers.Length; ++i)
  88. {
  89. // Choose a random segment if each background layer for level variety.
  90. int segmentIndex = levelIndex;
  91. layers[i] = Content.Load<Texture2D>("Backgrounds/Layer" + i + "_" + segmentIndex);
  92. }
  93. // Load sounds.
  94. exitReachedSound = Content.Load<SoundEffect>("Sounds/ExitReached");
  95. }
  96. /// <summary>
  97. /// Iterates over every tile in the structure file and loads its
  98. /// appearance and behavior. This method also validates that the
  99. /// file is well-formed with a player start point, exit, etc.
  100. /// </summary>
  101. /// <param name="fileStream">
  102. /// A stream containing the tile data.
  103. /// </param>
  104. private void LoadTiles(Stream fileStream)
  105. {
  106. // Load the level and ensure all of the lines are the same length.
  107. int width;
  108. List<string> lines = new List<string>();
  109. using (StreamReader reader = new StreamReader(fileStream))
  110. {
  111. string line = reader.ReadLine();
  112. width = line.Length;
  113. while (line != null)
  114. {
  115. lines.Add(line);
  116. if (line.Length != width)
  117. throw new Exception(String.Format("The length of line {0} is different from all preceeding lines.", lines.Count));
  118. line = reader.ReadLine();
  119. }
  120. }
  121. // Allocate the tile grid.
  122. tiles = new Tile[width, lines.Count];
  123. // Loop over every tile position,
  124. for (int y = 0; y < Height; ++y)
  125. {
  126. for (int x = 0; x < Width; ++x)
  127. {
  128. // to load each tile.
  129. char tileType = lines[y][x];
  130. tiles[x, y] = LoadTile(tileType, x, y);
  131. }
  132. }
  133. // Verify that the level has a beginning and an end.
  134. if (Player == null)
  135. throw new NotSupportedException("A level must have a starting point.");
  136. if (exit == InvalidPosition)
  137. throw new NotSupportedException("A level must have an exit.");
  138. }
  139. /// <summary>
  140. /// Loads an individual tile's appearance and behavior.
  141. /// </summary>
  142. /// <param name="tileType">
  143. /// The character loaded from the structure file which
  144. /// indicates what should be loaded.
  145. /// </param>
  146. /// <param name="x">
  147. /// The X location of this tile in tile space.
  148. /// </param>
  149. /// <param name="y">
  150. /// The Y location of this tile in tile space.
  151. /// </param>
  152. /// <returns>The loaded tile.</returns>
  153. private Tile LoadTile(char tileType, int x, int y)
  154. {
  155. switch (tileType)
  156. {
  157. // Blank space
  158. case '.':
  159. return new Tile(null, TileCollision.Passable);
  160. // Exit
  161. case 'X':
  162. return LoadExitTile(x, y);
  163. // Gem
  164. case 'G':
  165. return LoadGemTile(x, y);
  166. // Floating platform
  167. case '-':
  168. return LoadTile("Platform", TileCollision.Platform);
  169. // Various enemies
  170. case 'A':
  171. return LoadEnemyTile(x, y, "MonsterA");
  172. case 'B':
  173. return LoadEnemyTile(x, y, "MonsterB");
  174. case 'C':
  175. return LoadEnemyTile(x, y, "MonsterC");
  176. case 'D':
  177. return LoadEnemyTile(x, y, "MonsterD");
  178. // Platform block
  179. case '~':
  180. return LoadVarietyTile("BlockB", 2, TileCollision.Platform);
  181. // Passable block
  182. case ':':
  183. return LoadVarietyTile("BlockB", 2, TileCollision.Passable);
  184. // Player 1 start point
  185. case '1':
  186. return LoadStartTile(x, y);
  187. // Impassable block
  188. case '#':
  189. return LoadVarietyTile("BlockA", 7, TileCollision.Impassable);
  190. // Unknown tile type character
  191. default:
  192. throw new NotSupportedException(String.Format("Unsupported tile type character '{0}' at position {1}, {2}.", tileType, x, y));
  193. }
  194. }
  195. /// <summary>
  196. /// Creates a new tile. The other tile loading methods typically chain to this
  197. /// method after performing their special logic.
  198. /// </summary>
  199. /// <param name="name">
  200. /// Path to a tile texture relative to the Content/Tiles directory.
  201. /// </param>
  202. /// <param name="collision">
  203. /// The tile collision type for the new tile.
  204. /// </param>
  205. /// <returns>The new tile.</returns>
  206. private Tile LoadTile(string name, TileCollision collision)
  207. {
  208. return new Tile(Content.Load<Texture2D>("Tiles/" + name), collision);
  209. }
  210. /// <summary>
  211. /// Loads a tile with a random appearance.
  212. /// </summary>
  213. /// <param name="baseName">
  214. /// The content name prefix for this group of tile variations. Tile groups are
  215. /// name LikeThis0.png and LikeThis1.png and LikeThis2.png.
  216. /// </param>
  217. /// <param name="variationCount">
  218. /// The number of variations in this group.
  219. /// </param>
  220. private Tile LoadVarietyTile(string baseName, int variationCount, TileCollision collision)
  221. {
  222. int index = random.Next(variationCount);
  223. return LoadTile(baseName + index, collision);
  224. }
  225. /// <summary>
  226. /// Instantiates a player, puts him in the level, and remembers where to put him when he is resurrected.
  227. /// </summary>
  228. private Tile LoadStartTile(int x, int y)
  229. {
  230. if (Player != null)
  231. throw new NotSupportedException("A level may only have one starting point.");
  232. start = RectangleExtensions.GetBottomCenter(GetBounds(x, y));
  233. player = new Player(this, start);
  234. return new Tile(null, TileCollision.Passable);
  235. }
  236. /// <summary>
  237. /// Remembers the location of the level's exit.
  238. /// </summary>
  239. private Tile LoadExitTile(int x, int y)
  240. {
  241. if (exit != InvalidPosition)
  242. throw new NotSupportedException("A level may only have one exit.");
  243. exit = GetBounds(x, y).Center;
  244. return LoadTile("Exit", TileCollision.Passable);
  245. }
  246. /// <summary>
  247. /// Instantiates an enemy and puts him in the level.
  248. /// </summary>
  249. private Tile LoadEnemyTile(int x, int y, string spriteSet)
  250. {
  251. Vector2 position = RectangleExtensions.GetBottomCenter(GetBounds(x, y));
  252. enemies.Add(new Enemy(this, position, spriteSet));
  253. return new Tile(null, TileCollision.Passable);
  254. }
  255. /// <summary>
  256. /// Instantiates a gem and puts it in the level.
  257. /// </summary>
  258. private Tile LoadGemTile(int x, int y)
  259. {
  260. Point position = GetBounds(x, y).Center;
  261. gems.Add(new Gem(this, new Vector2(position.X, position.Y)));
  262. return new Tile(null, TileCollision.Passable);
  263. }
  264. /// <summary>
  265. /// Unloads the level content.
  266. /// </summary>
  267. public void Dispose()
  268. {
  269. Content.Unload();
  270. }
  271. #endregion
  272. #region Bounds and collision
  273. /// <summary>
  274. /// Gets the collision mode of the tile at a particular location.
  275. /// This method handles tiles outside of the levels boundries by making it
  276. /// impossible to escape past the left or right edges, but allowing things
  277. /// to jump beyond the top of the level and fall off the bottom.
  278. /// </summary>
  279. public TileCollision GetCollision(int x, int y)
  280. {
  281. // Prevent escaping past the level ends.
  282. if (x < 0 || x >= Width)
  283. return TileCollision.Impassable;
  284. // Allow jumping past the level top and falling through the bottom.
  285. if (y < 0 || y >= Height)
  286. return TileCollision.Passable;
  287. return tiles[x, y].Collision;
  288. }
  289. /// <summary>
  290. /// Gets the bounding rectangle of a tile in world space.
  291. /// </summary>
  292. public Rectangle GetBounds(int x, int y)
  293. {
  294. return new Rectangle(x * Tile.Width, y * Tile.Height, Tile.Width, Tile.Height);
  295. }
  296. /// <summary>
  297. /// Width of level measured in tiles.
  298. /// </summary>
  299. public int Width
  300. {
  301. get { return tiles.GetLength(0); }
  302. }
  303. /// <summary>
  304. /// Height of the level measured in tiles.
  305. /// </summary>
  306. public int Height
  307. {
  308. get { return tiles.GetLength(1); }
  309. }
  310. #endregion
  311. #region Update
  312. /// <summary>
  313. /// Updates all objects in the world, performs collision between them,
  314. /// and handles the time limit with scoring.
  315. /// </summary>
  316. public void Update(
  317. GameTime gameTime,
  318. KeyboardState keyboardState,
  319. GamePadState gamePadState,
  320. AccelerometerState accelState,
  321. DisplayOrientation orientation)
  322. {
  323. // Pause while the player is dead or time is expired.
  324. if (!Player.IsAlive || TimeRemaining == TimeSpan.Zero)
  325. {
  326. // Still want to perform physics on the player.
  327. Player.ApplyPhysics(gameTime);
  328. }
  329. else if (ReachedExit)
  330. {
  331. // Animate the time being converted into points.
  332. int seconds = (int)Math.Round(gameTime.ElapsedGameTime.TotalSeconds * 100.0f);
  333. seconds = Math.Min(seconds, (int)Math.Ceiling(TimeRemaining.TotalSeconds));
  334. timeRemaining -= TimeSpan.FromSeconds(seconds);
  335. score += seconds * PointsPerSecond;
  336. }
  337. else
  338. {
  339. timeRemaining -= gameTime.ElapsedGameTime;
  340. Player.Update(gameTime, keyboardState, gamePadState, accelState, orientation);
  341. UpdateGems(gameTime);
  342. // Falling off the bottom of the level kills the player.
  343. if (Player.BoundingRectangle.Top >= Height * Tile.Height)
  344. OnPlayerKilled(null);
  345. UpdateEnemies(gameTime);
  346. // The player has reached the exit if they are standing on the ground and
  347. // his bounding rectangle contains the center of the exit tile. They can only
  348. // exit when they have collected all of the gems.
  349. if (Player.IsAlive &&
  350. Player.IsOnGround &&
  351. Player.BoundingRectangle.Contains(exit))
  352. {
  353. OnExitReached();
  354. }
  355. }
  356. // Clamp the time remaining at zero.
  357. if (timeRemaining < TimeSpan.Zero)
  358. timeRemaining = TimeSpan.Zero;
  359. }
  360. /// <summary>
  361. /// Animates each gem and checks to allows the player to collect them.
  362. /// </summary>
  363. private void UpdateGems(GameTime gameTime)
  364. {
  365. for (int i = 0; i < gems.Count; ++i)
  366. {
  367. Gem gem = gems[i];
  368. gem.Update(gameTime);
  369. if (gem.BoundingCircle.Intersects(Player.BoundingRectangle))
  370. {
  371. gems.RemoveAt(i--);
  372. OnGemCollected(gem, Player);
  373. }
  374. }
  375. }
  376. /// <summary>
  377. /// Animates each enemy and allow them to kill the player.
  378. /// </summary>
  379. private void UpdateEnemies(GameTime gameTime)
  380. {
  381. foreach (Enemy enemy in enemies)
  382. {
  383. enemy.Update(gameTime);
  384. // Touching an enemy instantly kills the player
  385. if (enemy.BoundingRectangle.Intersects(Player.BoundingRectangle))
  386. {
  387. OnPlayerKilled(enemy);
  388. }
  389. }
  390. }
  391. /// <summary>
  392. /// Called when a gem is collected.
  393. /// </summary>
  394. /// <param name="gem">The gem that was collected.</param>
  395. /// <param name="collectedBy">The player who collected this gem.</param>
  396. private void OnGemCollected(Gem gem, Player collectedBy)
  397. {
  398. score += gem.PointValue;
  399. gem.OnCollected(collectedBy);
  400. }
  401. /// <summary>
  402. /// Called when the player is killed.
  403. /// </summary>
  404. /// <param name="killedBy">
  405. /// The enemy who killed the player. This is null if the player was not killed by an
  406. /// enemy, such as when a player falls into a hole.
  407. /// </param>
  408. private void OnPlayerKilled(Enemy killedBy)
  409. {
  410. Player.OnKilled(killedBy);
  411. }
  412. /// <summary>
  413. /// Called when the player reaches the level's exit.
  414. /// </summary>
  415. private void OnExitReached()
  416. {
  417. Player.OnReachedExit();
  418. exitReachedSound.Play();
  419. reachedExit = true;
  420. }
  421. /// <summary>
  422. /// Restores the player to the starting point to try the level again.
  423. /// </summary>
  424. public void StartNewLife()
  425. {
  426. Player.Reset(start);
  427. }
  428. #endregion
  429. #region Draw
  430. /// <summary>
  431. /// Draw everything in the level from background to foreground.
  432. /// </summary>
  433. public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
  434. {
  435. for (int i = 0; i <= EntityLayer; ++i)
  436. spriteBatch.Draw(layers[i], Vector2.Zero, Color.White);
  437. DrawTiles(spriteBatch);
  438. foreach (Gem gem in gems)
  439. gem.Draw(gameTime, spriteBatch);
  440. Player.Draw(gameTime, spriteBatch);
  441. foreach (Enemy enemy in enemies)
  442. enemy.Draw(gameTime, spriteBatch);
  443. for (int i = EntityLayer + 1; i < layers.Length; ++i)
  444. spriteBatch.Draw(layers[i], Vector2.Zero, Color.White);
  445. }
  446. /// <summary>
  447. /// Draws each tile in the level.
  448. /// </summary>
  449. private void DrawTiles(SpriteBatch spriteBatch)
  450. {
  451. // For each tile position
  452. for (int y = 0; y < Height; ++y)
  453. {
  454. for (int x = 0; x < Width; ++x)
  455. {
  456. // If there is a visible tile in that position
  457. Texture2D texture = tiles[x, y].Texture;
  458. if (texture != null)
  459. {
  460. // Draw it in screen space.
  461. Vector2 position = new Vector2(x, y) * Tile.Size;
  462. spriteBatch.Draw(texture, position, Color.White);
  463. }
  464. }
  465. }
  466. }
  467. #endregion
  468. }
  469. }