PlatformerGame.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // PlatformerGame.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.IO;
  11. #if ANDROID
  12. using Android.App;
  13. #endif
  14. using Microsoft.Xna.Framework;
  15. using Microsoft.Xna.Framework.Graphics;
  16. using Microsoft.Xna.Framework.Input;
  17. using Microsoft.Xna.Framework.Media;
  18. using Microsoft.Xna.Framework.Input.Touch;
  19. namespace Platformer
  20. {
  21. /// <summary>
  22. /// This is the main type for your game
  23. /// </summary>
  24. public class PlatformerGame : Microsoft.Xna.Framework.Game
  25. {
  26. // Resources for drawing.
  27. private GraphicsDeviceManager graphics;
  28. private SpriteBatch spriteBatch;
  29. // Global content.
  30. private SpriteFont hudFont;
  31. private Texture2D winOverlay;
  32. private Texture2D loseOverlay;
  33. private Texture2D diedOverlay;
  34. // Meta-level game state.
  35. private int levelIndex = -1;
  36. private Level level;
  37. private bool wasContinuePressed;
  38. // When the time remaining is less than the warning time, it blinks on the hud
  39. private static readonly TimeSpan WarningTime = TimeSpan.FromSeconds(30);
  40. // We store our input states so that we only poll once per frame,
  41. // then we use the same input state wherever needed
  42. private GamePadState gamePadState;
  43. private KeyboardState keyboardState;
  44. private TouchCollection touchState;
  45. private AccelerometerState accelerometerState;
  46. // The number of levels in the Levels directory of our content. We assume that
  47. // levels in our content are 0-based and that all numbers under this constant
  48. // have a level file present. This allows us to not need to check for the file
  49. // or handle exceptions, both of which can add unnecessary time to level loading.
  50. private const int numberOfLevels = 3;
  51. #if ANDROID
  52. public PlatformerGame (Activity activity) : base (activity)
  53. #else
  54. public PlatformerGame()
  55. #endif
  56. {
  57. graphics = new GraphicsDeviceManager(this);
  58. Content.RootDirectory = "Content";
  59. #if WINDOWS_PHONE || ANDROID
  60. TargetElapsedTime = TimeSpan.FromTicks(333333);
  61. #endif
  62. #if MONOMAC
  63. graphics.PreferredBackBufferWidth = 800;
  64. graphics.PreferredBackBufferHeight = 480;
  65. #else
  66. graphics.IsFullScreen = true;
  67. graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight;
  68. #endif
  69. Accelerometer.Initialize();
  70. }
  71. /// <summary>
  72. /// LoadContent will be called once per game and is the place to load
  73. /// all of your content.
  74. /// </summary>
  75. protected override void LoadContent()
  76. {
  77. // Create a new SpriteBatch, which can be used to draw textures.
  78. spriteBatch = new SpriteBatch(GraphicsDevice);
  79. // Load fonts
  80. hudFont = Content.Load<SpriteFont>("Fonts/Hud");
  81. // Load overlay textures
  82. winOverlay = Content.Load<Texture2D>("Overlays/you_win");
  83. loseOverlay = Content.Load<Texture2D>("Overlays/you_lose");
  84. diedOverlay = Content.Load<Texture2D>("Overlays/you_died");
  85. //Known issue that you get exceptions if you use Media PLayer while connected to your PC
  86. //See http://social.msdn.microsoft.com/Forums/en/windowsphone7series/thread/c8a243d2-d360-46b1-96bd-62b1ef268c66
  87. //Which means its impossible to test this from VS.
  88. //So we have to catch the exception and throw it away
  89. try
  90. {
  91. MediaPlayer.IsRepeating = true;
  92. MediaPlayer.Play(Content.Load<Song>("Sounds/Music"));
  93. }
  94. catch { }
  95. LoadNextLevel();
  96. }
  97. /// <summary>
  98. /// Allows the game to run logic such as updating the world,
  99. /// checking for collisions, gathering input, and playing audio.
  100. /// </summary>
  101. /// <param name="gameTime">Provides a snapshot of timing values.</param>
  102. protected override void Update(GameTime gameTime)
  103. {
  104. // Handle polling for our input and handling high-level input
  105. HandleInput();
  106. // update our level, passing down the GameTime along with all of our input states
  107. level.Update(gameTime, keyboardState, gamePadState, touchState,
  108. accelerometerState, Window.CurrentOrientation);
  109. base.Update(gameTime);
  110. }
  111. private void HandleInput()
  112. {
  113. // get all of our input states
  114. keyboardState = Keyboard.GetState();
  115. gamePadState = GamePad.GetState(PlayerIndex.One);
  116. touchState = TouchPanel.GetState();
  117. accelerometerState = Accelerometer.GetState();
  118. // Exit the game when back is pressed.
  119. if (gamePadState.Buttons.Back == ButtonState.Pressed)
  120. Exit();
  121. bool continuePressed =
  122. keyboardState.IsKeyDown(Keys.Space) ||
  123. gamePadState.IsButtonDown(Buttons.A) ||
  124. touchState.AnyTouch();
  125. // Perform the appropriate action to advance the game and
  126. // to get the player back to playing.
  127. if (!wasContinuePressed && continuePressed)
  128. {
  129. if (!level.Player.IsAlive)
  130. {
  131. level.StartNewLife();
  132. }
  133. else if (level.TimeRemaining == TimeSpan.Zero)
  134. {
  135. if (level.ReachedExit)
  136. LoadNextLevel();
  137. else
  138. ReloadCurrentLevel();
  139. }
  140. }
  141. wasContinuePressed = continuePressed;
  142. }
  143. private void LoadNextLevel()
  144. {
  145. // move to the next level
  146. levelIndex = (levelIndex + 1) % numberOfLevels;
  147. // Unloads the content for the current level before loading the next one.
  148. if (level != null)
  149. level.Dispose();
  150. // Load the level.
  151. string levelPath = string.Format("{0}/Levels/{1}.txt", Content.RootDirectory, levelIndex);
  152. using (Stream fileStream = TitleContainer.OpenStream(levelPath))
  153. level = new Level(Services, fileStream, levelIndex);
  154. }
  155. private void ReloadCurrentLevel()
  156. {
  157. --levelIndex;
  158. LoadNextLevel();
  159. }
  160. /// <summary>
  161. /// Draws the game from background to foreground.
  162. /// </summary>
  163. /// <param name="gameTime">Provides a snapshot of timing values.</param>
  164. protected override void Draw(GameTime gameTime)
  165. {
  166. graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
  167. spriteBatch.Begin();
  168. level.Draw(gameTime, spriteBatch);
  169. DrawHud();
  170. GamePad.Draw(gameTime, spriteBatch);
  171. spriteBatch.End();
  172. base.Draw(gameTime);
  173. }
  174. private void DrawHud()
  175. {
  176. Rectangle titleSafeArea = GraphicsDevice.Viewport.TitleSafeArea;
  177. Vector2 hudLocation = new Vector2(titleSafeArea.X, titleSafeArea.Y);
  178. Vector2 center = new Vector2(titleSafeArea.X + titleSafeArea.Width / 2.0f,
  179. titleSafeArea.Y + titleSafeArea.Height / 2.0f);
  180. // Draw time remaining. Uses modulo division to cause blinking when the
  181. // player is running out of time.
  182. string timeString = "TIME: " + level.TimeRemaining.Minutes.ToString("00") + ":" + level.TimeRemaining.Seconds.ToString("00");
  183. Color timeColor;
  184. if (level.TimeRemaining > WarningTime ||
  185. level.ReachedExit ||
  186. (int)level.TimeRemaining.TotalSeconds % 2 == 0)
  187. {
  188. timeColor = Color.Yellow;
  189. }
  190. else
  191. {
  192. timeColor = Color.Red;
  193. }
  194. DrawShadowedString(hudFont, timeString, hudLocation, timeColor);
  195. // Draw score
  196. float timeHeight = hudFont.MeasureString(timeString).Y;
  197. DrawShadowedString(hudFont, "SCORE: " + level.Score.ToString(), hudLocation + new Vector2(0.0f, timeHeight * 1.2f), Color.Yellow);
  198. // Determine the status overlay message to show.
  199. Texture2D status = null;
  200. if (level.TimeRemaining == TimeSpan.Zero)
  201. {
  202. if (level.ReachedExit)
  203. {
  204. status = winOverlay;
  205. }
  206. else
  207. {
  208. status = loseOverlay;
  209. }
  210. }
  211. else if (!level.Player.IsAlive)
  212. {
  213. status = diedOverlay;
  214. }
  215. if (status != null)
  216. {
  217. // Draw status message.
  218. Vector2 statusSize = new Vector2(status.Width, status.Height);
  219. spriteBatch.Draw(status, center - statusSize / 2, Color.White);
  220. }
  221. }
  222. private void DrawShadowedString(SpriteFont font, string value, Vector2 position, Color color)
  223. {
  224. spriteBatch.DrawString(font, value, position + new Vector2(1.0f, 1.0f), Color.Black);
  225. spriteBatch.DrawString(font, value, position, color);
  226. }
  227. }
  228. }