GameplayScreen.cs 9.3 KB

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