PlatformerGame.cs 11 KB

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