GameplayScreen.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // GameplayScreen.cs
  4. //
  5. // Microsoft XNA Community Game Platform
  6. // Copyright (C) Microsoft Corporation. All rights reserved.
  7. //-----------------------------------------------------------------------------
  8. #endregion
  9. #region Using Statements
  10. using System;
  11. using System.Threading;
  12. using Microsoft.Xna.Framework;
  13. using Microsoft.Xna.Framework.Content;
  14. using Microsoft.Xna.Framework.Graphics;
  15. using Microsoft.Xna.Framework.Input;
  16. using GameStateManagement;
  17. #endregion
  18. namespace GameStateManagementSample
  19. {
  20. /// <summary>
  21. /// This screen implements the actual game logic. It is just a
  22. /// placeholder to get the idea across: you'll probably want to
  23. /// put some more interesting gameplay in here!
  24. /// </summary>
  25. class GameplayScreen : GameScreen
  26. {
  27. #region Fields
  28. ContentManager content;
  29. SpriteFont gameFont;
  30. Vector2 playerPosition = new Vector2(100, 100);
  31. Vector2 enemyPosition = new Vector2(100, 100);
  32. Random random = new Random();
  33. float pauseAlpha;
  34. InputAction pauseAction;
  35. #endregion
  36. #region Initialization
  37. /// <summary>
  38. /// Constructor.
  39. /// </summary>
  40. public GameplayScreen()
  41. {
  42. TransitionOnTime = TimeSpan.FromSeconds(1.5);
  43. TransitionOffTime = TimeSpan.FromSeconds(0.5);
  44. pauseAction = new InputAction(
  45. new Buttons[] { Buttons.Start, Buttons.Back },
  46. new Keys[] { Keys.Escape },
  47. true);
  48. }
  49. /// <summary>
  50. /// Load graphics content for the game.
  51. /// </summary>
  52. public override void Activate(bool instancePreserved)
  53. {
  54. if (!instancePreserved)
  55. {
  56. if (content == null)
  57. content = new ContentManager(ScreenManager.Game.Services, "Content");
  58. gameFont = content.Load<SpriteFont>("gamefont");
  59. // A real game would probably have more content than this sample, so
  60. // it would take longer to load. We simulate that by delaying for a
  61. // while, giving you a chance to admire the beautiful loading screen.
  62. #if !WINDOWS_UAP
  63. Thread.Sleep(1000);
  64. #endif
  65. // once the load has finished, we use ResetElapsedTime to tell the game's
  66. // timing mechanism that we have just finished a very long frame, and that
  67. // it should not try to catch up.
  68. ScreenManager.Game.ResetElapsedTime();
  69. }
  70. #if WINDOWS_PHONE
  71. if (Microsoft.Phone.Shell.PhoneApplicationService.Current.State.ContainsKey("PlayerPosition"))
  72. {
  73. playerPosition = (Vector2)Microsoft.Phone.Shell.PhoneApplicationService.Current.State["PlayerPosition"];
  74. enemyPosition = (Vector2)Microsoft.Phone.Shell.PhoneApplicationService.Current.State["EnemyPosition"];
  75. }
  76. #endif
  77. }
  78. public override void Deactivate()
  79. {
  80. #if WINDOWS_PHONE
  81. Microsoft.Phone.Shell.PhoneApplicationService.Current.State["PlayerPosition"] = playerPosition;
  82. Microsoft.Phone.Shell.PhoneApplicationService.Current.State["EnemyPosition"] = enemyPosition;
  83. #endif
  84. base.Deactivate();
  85. }
  86. /// <summary>
  87. /// Unload graphics content used by the game.
  88. /// </summary>
  89. public override void Unload()
  90. {
  91. content.Unload();
  92. #if WINDOWS_PHONE
  93. Microsoft.Phone.Shell.PhoneApplicationService.Current.State.Remove("PlayerPosition");
  94. Microsoft.Phone.Shell.PhoneApplicationService.Current.State.Remove("EnemyPosition");
  95. #endif
  96. }
  97. #endregion
  98. #region Update and Draw
  99. /// <summary>
  100. /// Updates the state of the game. This method checks the GameScreen.IsActive
  101. /// property, so the game will stop updating when the pause menu is active,
  102. /// or if you tab away to a different application.
  103. /// </summary>
  104. public override void Update(GameTime gameTime, bool otherScreenHasFocus,
  105. bool coveredByOtherScreen)
  106. {
  107. base.Update(gameTime, otherScreenHasFocus, false);
  108. // Gradually fade in or out depending on whether we are covered by the pause screen.
  109. if (coveredByOtherScreen)
  110. pauseAlpha = Math.Min(pauseAlpha + 1f / 32, 1);
  111. else
  112. pauseAlpha = Math.Max(pauseAlpha - 1f / 32, 0);
  113. if (IsActive)
  114. {
  115. // Apply some random jitter to make the enemy move around.
  116. const float randomization = 10;
  117. enemyPosition.X += (float)(random.NextDouble() - 0.5) * randomization;
  118. enemyPosition.Y += (float)(random.NextDouble() - 0.5) * randomization;
  119. // Apply a stabilizing force to stop the enemy moving off the screen.
  120. Vector2 targetPosition = new Vector2(
  121. ScreenManager.GraphicsDevice.Viewport.Width / 2 - gameFont.MeasureString("Insert Gameplay Here").X / 2,
  122. 200);
  123. enemyPosition = Vector2.Lerp(enemyPosition, targetPosition, 0.05f);
  124. // TODO: this game isn't very fun! You could probably improve
  125. // it by inserting something more interesting in this space :-)
  126. }
  127. }
  128. /// <summary>
  129. /// Lets the game respond to player input. Unlike the Update method,
  130. /// this will only be called when the gameplay screen is active.
  131. /// </summary>
  132. public override void HandleInput(GameTime gameTime, InputState input)
  133. {
  134. if (input == null)
  135. throw new ArgumentNullException("input");
  136. // Look up inputs for the active player profile.
  137. int playerIndex = (int)ControllingPlayer.Value;
  138. KeyboardState keyboardState = input.CurrentKeyboardStates[playerIndex];
  139. GamePadState gamePadState = input.CurrentGamePadStates[playerIndex];
  140. // The game pauses either if the user presses the pause button, or if
  141. // they unplug the active gamepad. This requires us to keep track of
  142. // whether a gamepad was ever plugged in, because we don't want to pause
  143. // on PC if they are playing with a keyboard and have no gamepad at all!
  144. bool gamePadDisconnected = !gamePadState.IsConnected &&
  145. input.GamePadWasConnected[playerIndex];
  146. PlayerIndex player;
  147. if (pauseAction.Evaluate(input, ControllingPlayer, out player) || gamePadDisconnected)
  148. {
  149. #if WINDOWS_PHONE
  150. ScreenManager.AddScreen(new PhonePauseScreen(), ControllingPlayer);
  151. #else
  152. ScreenManager.AddScreen(new PauseMenuScreen(), ControllingPlayer);
  153. #endif
  154. }
  155. else
  156. {
  157. // Otherwise move the player position.
  158. Vector2 movement = Vector2.Zero;
  159. if (keyboardState.IsKeyDown(Keys.Left))
  160. movement.X--;
  161. if (keyboardState.IsKeyDown(Keys.Right))
  162. movement.X++;
  163. if (keyboardState.IsKeyDown(Keys.Up))
  164. movement.Y--;
  165. if (keyboardState.IsKeyDown(Keys.Down))
  166. movement.Y++;
  167. Vector2 thumbstick = gamePadState.ThumbSticks.Left;
  168. movement.X += thumbstick.X;
  169. movement.Y -= thumbstick.Y;
  170. if (input.TouchState.Count > 0)
  171. {
  172. Vector2 touchPosition = input.TouchState[0].Position;
  173. Vector2 direction = touchPosition - playerPosition;
  174. direction.Normalize();
  175. movement += direction;
  176. }
  177. if (movement.Length() > 1)
  178. movement.Normalize();
  179. playerPosition += movement * 8f;
  180. }
  181. }
  182. /// <summary>
  183. /// Draws the gameplay screen.
  184. /// </summary>
  185. public override void Draw(GameTime gameTime)
  186. {
  187. // This game has a blue background. Why? Because!
  188. ScreenManager.GraphicsDevice.Clear(ClearOptions.Target,
  189. Color.CornflowerBlue, 0, 0);
  190. // Our player and enemy are both actually just text strings.
  191. SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
  192. spriteBatch.Begin();
  193. spriteBatch.DrawString(gameFont, "// TODO", playerPosition, Color.Green);
  194. spriteBatch.DrawString(gameFont, "Insert Gameplay Here",
  195. enemyPosition, Color.DarkRed);
  196. spriteBatch.End();
  197. // If the game is transitioning on or off, fade it out to black.
  198. if (TransitionPosition > 0 || pauseAlpha > 0)
  199. {
  200. float alpha = MathHelper.Lerp(1f - TransitionAlpha, 1f, pauseAlpha / 2);
  201. ScreenManager.FadeBackBufferToBlack(alpha);
  202. }
  203. }
  204. #endregion
  205. }
  206. }