SpacewarGame.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // SpacewarGame.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.Collections.Generic;
  12. using Microsoft.Xna.Framework;
  13. using Microsoft.Xna.Framework.Content;
  14. using Microsoft.Xna.Framework.Audio;
  15. using Microsoft.Xna.Framework.Graphics;
  16. using Microsoft.Xna.Framework.Input;
  17. using Microsoft.Xna.Framework.Storage;
  18. #endregion
  19. namespace Spacewar
  20. {
  21. /// <summary>
  22. /// This is the main type for your game
  23. /// </summary>
  24. partial class SpacewarGame : Microsoft.Xna.Framework.Game
  25. {
  26. // these are the size of the offscreen drawing surface
  27. // in general, no one wants to change these as there
  28. // are all kinds of UI calculations and positions based
  29. // on these dimensions.
  30. const int FixedDrawingWidth = 1280;
  31. const int FixedDrawingHeight = 720;
  32. // these are the size of the output window, ignored
  33. // on Xbox 360
  34. private int preferredWindowWidth = 1280;
  35. private int preferredWindowHeight = 720;
  36. private static ContentManager contentManager;
  37. /// <summary>
  38. /// The game settings from settings.xml
  39. /// </summary>
  40. private static Settings settings = new Settings();
  41. private static Camera camera;
  42. /// <summary>
  43. /// Information about the players such as score, health etc
  44. /// </summary>
  45. private static Player[] players;
  46. /// <summary>
  47. /// The current game state
  48. /// </summary>
  49. private static GameState gameState = GameState.Started;
  50. /// <summary>
  51. /// Which game board are we playing on
  52. /// </summary>
  53. private static int gameLevel;
  54. /// <summary>
  55. /// Stores game paused state
  56. /// </summary>
  57. private bool paused;
  58. private GraphicsDeviceManager graphics;
  59. private bool enableDrawScaling;
  60. private RenderTarget2D drawBuffer;
  61. private SpriteBatch spriteBatch;
  62. private static Screen currentScreen;
  63. private static PlatformID currentPlatform;
  64. private static KeyboardState keyState;
  65. private bool justWentFullScreen;
  66. #region Properties
  67. public static GameState GameState
  68. {
  69. get
  70. {
  71. return gameState;
  72. }
  73. }
  74. public static int GameLevel
  75. {
  76. get
  77. {
  78. return gameLevel;
  79. }
  80. set
  81. {
  82. gameLevel = value;
  83. }
  84. }
  85. public static Camera Camera
  86. {
  87. get
  88. {
  89. return camera;
  90. }
  91. }
  92. public static Settings Settings
  93. {
  94. get
  95. {
  96. return settings;
  97. }
  98. }
  99. public static Player[] Players
  100. {
  101. get
  102. {
  103. return players;
  104. }
  105. }
  106. public static ContentManager ContentManager
  107. {
  108. get
  109. {
  110. return contentManager;
  111. }
  112. }
  113. public static PlatformID CurrentPlatform
  114. {
  115. get
  116. {
  117. return currentPlatform;
  118. }
  119. }
  120. public static KeyboardState KeyState
  121. {
  122. get
  123. {
  124. return keyState;
  125. }
  126. }
  127. #endregion
  128. public SpacewarGame()
  129. {
  130. #if XBOX360
  131. // we might as well use the xbox in all its glory
  132. preferredWindowWidth = FixedDrawingWidth;
  133. preferredWindowHeight = FixedDrawingHeight;
  134. enableDrawScaling = false;
  135. #else
  136. enableDrawScaling = true;
  137. #endif
  138. this.graphics = new Microsoft.Xna.Framework.GraphicsDeviceManager(this);
  139. this.graphics.PreferredBackBufferWidth = preferredWindowWidth;
  140. this.graphics.PreferredBackBufferHeight = preferredWindowHeight;
  141. // Game should run as fast as possible.
  142. IsFixedTimeStep = false;
  143. }
  144. protected override void Initialize()
  145. {
  146. // game initialization code here
  147. //Uncomment this line to force a save of the default settings file. Useful when you had added things to settings.cs
  148. //NOTE in VS this will go in DEBUG or RELEASE - need to copy up to main project
  149. //Settings.Save("settings.xml");
  150. settings = Settings.Load("settings.xml");
  151. currentPlatform = System.Environment.OSVersion.Platform;
  152. //Initialise the sound
  153. Sound.Initialize();
  154. Window.Title = Settings.WindowTitle;
  155. base.Initialize();
  156. }
  157. protected override void BeginRun()
  158. {
  159. Sound.PlayCue(Sounds.TitleMusic);
  160. //Kick off the game by loading the logo splash screen
  161. ChangeState(GameState.LogoSplash);
  162. float fieldOfView = (float)Math.PI / 4;
  163. float aspectRatio = (float)FixedDrawingWidth / (float)FixedDrawingHeight;
  164. float nearPlane = 10f;
  165. float farPlane = 700f;
  166. camera = new Camera(fieldOfView, aspectRatio, nearPlane, farPlane);
  167. camera.ViewPosition = new Vector3(0, 0, 500);
  168. base.BeginRun();
  169. }
  170. protected override void Update(GameTime gameTime)
  171. {
  172. TimeSpan elapsedTime = gameTime.ElapsedGameTime;
  173. TimeSpan time = gameTime.TotalGameTime;
  174. // The time since Update was called last
  175. float elapsed = (float)elapsedTime.TotalSeconds;
  176. GameState changeState = GameState.None;
  177. keyState = Keyboard.GetState();
  178. XInputHelper.Update(this, keyState);
  179. if ((keyState.IsKeyDown(Keys.RightAlt) || keyState.IsKeyDown(Keys.LeftAlt)) && keyState.IsKeyDown(Keys.Enter) && !justWentFullScreen)
  180. {
  181. ToggleFullScreen();
  182. justWentFullScreen = true;
  183. }
  184. if (keyState.IsKeyUp(Keys.Enter))
  185. {
  186. justWentFullScreen = false;
  187. }
  188. if (XInputHelper.GamePads[PlayerIndex.One].BackPressed ||
  189. XInputHelper.GamePads[PlayerIndex.Two].BackPressed)
  190. {
  191. if (gameState == GameState.PlayEvolved || gameState == GameState.PlayRetro)
  192. {
  193. paused = !paused;
  194. }
  195. if (gameState == GameState.LogoSplash)
  196. {
  197. this.Exit();
  198. }
  199. }
  200. //Reload settings file?
  201. if (XInputHelper.GamePads[PlayerIndex.One].YPressed)
  202. {
  203. //settings = Settings.Load("settings.xml");
  204. //GC.Collect();
  205. }
  206. if (!paused)
  207. {
  208. //Update everything
  209. changeState = currentScreen.Update(time, elapsedTime);
  210. // Update the AudioEngine - MUST call this every frame!!
  211. Sound.Update();
  212. //If either player presses start then reset the game
  213. if (XInputHelper.GamePads[PlayerIndex.One].StartPressed ||
  214. XInputHelper.GamePads[PlayerIndex.Two].StartPressed)
  215. {
  216. changeState = GameState.LogoSplash;
  217. }
  218. if (changeState != GameState.None)
  219. {
  220. ChangeState(changeState);
  221. }
  222. }
  223. base.Update(gameTime);
  224. }
  225. protected override bool BeginDraw()
  226. {
  227. if (!base.BeginDraw())
  228. return false;
  229. BeginDrawScaling();
  230. return true;
  231. }
  232. protected override void Draw(GameTime gameTime)
  233. {
  234. graphics.GraphicsDevice.Clear(ClearOptions.DepthBuffer,
  235. Color.CornflowerBlue, 1.0f, 0);
  236. base.Draw(gameTime);
  237. currentScreen.Render();
  238. }
  239. protected override void EndDraw()
  240. {
  241. EndDrawScaling();
  242. base.EndDraw();
  243. }
  244. internal void ChangeState(GameState NextState)
  245. {
  246. //Logo spash can come from ANY state since its the place you go when you restart
  247. if (NextState == GameState.LogoSplash)
  248. {
  249. if (currentScreen != null)
  250. currentScreen.Shutdown();
  251. currentScreen = new TitleScreen(this);
  252. gameState = GameState.LogoSplash;
  253. }
  254. else if (gameState == GameState.LogoSplash && NextState == GameState.ShipSelection)
  255. {
  256. Sound.PlayCue(Sounds.MenuAdvance);
  257. //This is really where the game starts so setup the player information
  258. players = new Player[2] { new Player(), new Player() };
  259. //Start at level 1
  260. gameLevel = 1;
  261. currentScreen.Shutdown();
  262. currentScreen = new SelectionScreen(this);
  263. gameState = GameState.ShipSelection;
  264. }
  265. else if (gameState == GameState.PlayEvolved && NextState == GameState.ShipUpgrade)
  266. {
  267. currentScreen.Shutdown();
  268. currentScreen = new ShipUpgradeScreen(this);
  269. gameState = GameState.ShipUpgrade;
  270. }
  271. else if ((gameState == GameState.ShipSelection || GameState == GameState.ShipUpgrade) && NextState == GameState.PlayEvolved)
  272. {
  273. Sound.PlayCue(Sounds.MenuAdvance);
  274. currentScreen.Shutdown();
  275. currentScreen = new EvolvedScreen(this);
  276. gameState = GameState.PlayEvolved;
  277. }
  278. else if (gameState == GameState.LogoSplash && NextState == GameState.PlayRetro)
  279. {
  280. //Game starts here for retro
  281. players = new Player[2] { new Player(), new Player() };
  282. currentScreen.Shutdown();
  283. currentScreen = new RetroScreen(this);
  284. gameState = GameState.PlayRetro;
  285. }
  286. else if (gameState == GameState.PlayEvolved && NextState == GameState.Victory)
  287. {
  288. currentScreen.Shutdown();
  289. currentScreen = new VictoryScreen(this);
  290. gameState = GameState.Victory;
  291. }
  292. else
  293. {
  294. //This is a BAD thing and should never happen
  295. // What does this map to on XBox 360?
  296. //Debug.Assert(false, String.Format("Invalid State transition {0} to {1}", gameState.ToString(), NextState.ToString()));
  297. }
  298. }
  299. protected override void LoadContent()
  300. {
  301. base.LoadContent();
  302. contentManager = new ContentManager(Services);
  303. if (currentScreen != null)
  304. currentScreen.OnCreateDevice();
  305. Font.Init(this);
  306. if (enableDrawScaling)
  307. {
  308. PresentationParameters pp = graphics.GraphicsDevice.PresentationParameters;
  309. drawBuffer = new RenderTarget2D(graphics.GraphicsDevice,
  310. FixedDrawingWidth, FixedDrawingHeight,
  311. true, SurfaceFormat.Color,
  312. DepthFormat.Depth24Stencil8, pp.MultiSampleCount,
  313. RenderTargetUsage.DiscardContents);
  314. spriteBatch = new SpriteBatch(graphics.GraphicsDevice);
  315. }
  316. }
  317. protected override void UnloadContent()
  318. {
  319. base.UnloadContent();
  320. if (drawBuffer != null)
  321. {
  322. drawBuffer.Dispose();
  323. drawBuffer = null;
  324. }
  325. if (spriteBatch != null)
  326. {
  327. spriteBatch.Dispose();
  328. spriteBatch = null;
  329. }
  330. Font.Dispose();
  331. if (contentManager != null)
  332. {
  333. contentManager.Dispose();
  334. contentManager = null;
  335. }
  336. }
  337. private void ToggleFullScreen()
  338. {
  339. PresentationParameters presentation = graphics.GraphicsDevice.PresentationParameters;
  340. if (presentation.IsFullScreen)
  341. { // going windowed
  342. graphics.PreferredBackBufferWidth = preferredWindowWidth;
  343. graphics.PreferredBackBufferHeight = preferredWindowHeight;
  344. }
  345. else
  346. {
  347. // going fullscreen, use desktop resolution to minimize display mode changes
  348. // this also has the nice effect of working around some displays that lie about
  349. // supporting 1280x720
  350. GraphicsAdapter adapter = graphics.GraphicsDevice.Adapter;
  351. graphics.PreferredBackBufferWidth = adapter.CurrentDisplayMode.Width;
  352. graphics.PreferredBackBufferHeight = adapter.CurrentDisplayMode.Height;
  353. }
  354. graphics.ToggleFullScreen();
  355. }
  356. private void BeginDrawScaling()
  357. {
  358. if (enableDrawScaling && drawBuffer != null)
  359. {
  360. graphics.GraphicsDevice.SetRenderTarget(drawBuffer);
  361. }
  362. }
  363. private void EndDrawScaling()
  364. {
  365. // copy our offscreen surface to the backbuffer with appropriate
  366. // letterbox bars
  367. if (!enableDrawScaling || drawBuffer == null)
  368. return;
  369. graphics.GraphicsDevice.SetRenderTarget(null);
  370. PresentationParameters presentation = graphics.GraphicsDevice.PresentationParameters;
  371. float outputAspect = (float)presentation.BackBufferWidth / (float)presentation.BackBufferHeight;
  372. float preferredAspect = (float)FixedDrawingWidth / (float)FixedDrawingHeight;
  373. Rectangle dst;
  374. if (outputAspect <= preferredAspect)
  375. {
  376. // output is taller than it is wider, bars on top/bottom
  377. int presentHeight = (int)((presentation.BackBufferWidth / preferredAspect) + 0.5f);
  378. int barHeight = (presentation.BackBufferHeight - presentHeight) / 2;
  379. dst = new Rectangle(0, barHeight, presentation.BackBufferWidth, presentHeight);
  380. }
  381. else
  382. {
  383. // output is wider than it is tall, bars left/right
  384. int presentWidth = (int)((presentation.BackBufferHeight * preferredAspect) + 0.5f);
  385. int barWidth = (presentation.BackBufferWidth - presentWidth) / 2;
  386. dst = new Rectangle(barWidth, 0, presentWidth, presentation.BackBufferHeight);
  387. }
  388. // clear to get black bars
  389. graphics.GraphicsDevice.Clear(ClearOptions.Target, Color.Black, 1.0f, 0);
  390. // draw a quad to get the draw buffer to the back buffer
  391. spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque);
  392. spriteBatch.Draw(drawBuffer, dst, Color.White);
  393. spriteBatch.End();
  394. }
  395. }
  396. }