FuelCellGame.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // FuelCellGame.cs
  4. //
  5. // Microsoft XNA Community Game Platform
  6. // Copyright (C) Microsoft Corporation. All rights reserved.
  7. //-----------------------------------------------------------------------------
  8. #endregion
  9. using Microsoft.Xna.Framework;
  10. using Microsoft.Xna.Framework.Audio;
  11. using Microsoft.Xna.Framework.Graphics;
  12. using Microsoft.Xna.Framework.Input;
  13. using Microsoft.Xna.Framework.Media;
  14. using System;
  15. using MediaPlayer = Microsoft.Xna.Framework.Media.MediaPlayer;
  16. namespace FuelCell
  17. {
  18. /// <summary>
  19. /// The available states of the game
  20. /// </summary>
  21. public enum GameState { Loading, Running, Won, Lost }
  22. /// <summary>
  23. /// This is the main type for your game
  24. /// </summary>
  25. public class FuelCellGame : Game
  26. {
  27. // Resources for drawing.
  28. private GraphicsDeviceManager graphics;
  29. private SpriteBatch spriteBatch;
  30. private SpriteFont statsFont;
  31. private GameObject ground;
  32. private Camera gameCamera;
  33. private Random random;
  34. private GameState currentGameState = GameState.Loading;
  35. // Game objects
  36. private FuelCarrier fuelCarrier;
  37. private FuelCell[] fuelCells;
  38. private Barrier[] barriers;
  39. private GameObject boundingSphere;
  40. private int retrievedFuelCells = 0;
  41. private TimeSpan startTime, roundTimer, roundTime;
  42. private float aspectRatio;
  43. private IInputState inputState;
  44. private Song backgroundMusic;
  45. public FuelCellGame()
  46. {
  47. graphics = new GraphicsDeviceManager(this);
  48. Content.RootDirectory = "Content";
  49. random = new Random();
  50. roundTime = GameConstants.RoundTime;
  51. graphics.PreferredBackBufferWidth = 853;
  52. graphics.PreferredBackBufferHeight = 480;
  53. inputState = new InputState(this);
  54. }
  55. protected override void Initialize()
  56. {
  57. // Initialize the Game objects
  58. ground = new GameObject();
  59. gameCamera = new Camera();
  60. boundingSphere = new GameObject();
  61. aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;
  62. base.Initialize();
  63. }
  64. /// <summary>
  65. /// LoadContent will be called once per game and is the place to load
  66. /// all of your content.
  67. /// </summary>
  68. protected override void LoadContent()
  69. {
  70. this.Content.RootDirectory = "Content";
  71. // Create a new SpriteBatch, which can be used to draw textures.
  72. spriteBatch = new SpriteBatch(GraphicsDevice);
  73. statsFont = Content.Load<SpriteFont>("Fonts/StatsFont");
  74. ground.Model = Content.Load<Model>("Models/ground");
  75. boundingSphere.Model = Content.Load<Model>("Models/sphere1uR");
  76. // Audio
  77. backgroundMusic = Content.Load<Song>("Audio/background-music");
  78. //Initialize fuel cells
  79. fuelCells = new FuelCell[GameConstants.NumFuelCells];
  80. for (int index = 0; index < fuelCells.Length; index++)
  81. {
  82. fuelCells[index] = new FuelCell();
  83. fuelCells[index].LoadContent(Content, "Models/fuelcellmodel");
  84. }
  85. //Initialize barriers
  86. barriers = new Barrier[GameConstants.NumBarriers];
  87. int randomBarrier = random.Next(3);
  88. string barrierName = null;
  89. for (int index = 0; index < barriers.Length; index++)
  90. {
  91. switch (randomBarrier)
  92. {
  93. case 0:
  94. barrierName = "Models/cube10uR";
  95. break;
  96. case 1:
  97. barrierName = "Models/cylinder10uR";
  98. break;
  99. case 2:
  100. barrierName = "Models/pyramid10uR";
  101. break;
  102. }
  103. barriers[index] = new Barrier();
  104. barriers[index].LoadContent(Content, barrierName);
  105. randomBarrier = random.Next(3);
  106. }
  107. PlaceFuelCellsAndBarriers();
  108. //Initialize fuel carrier
  109. fuelCarrier = new FuelCarrier();
  110. fuelCarrier.LoadContent(Content, "Models/fuelcarrier");
  111. }
  112. /// <summary>
  113. /// Allows the game to run logic such as updating the world,
  114. /// checking for collisions, gathering input, and playing audio.
  115. /// </summary>
  116. /// <param name="gameTime">Provides a snapshot of timing values.</param>
  117. protected override void Update(GameTime gameTime)
  118. {
  119. // Update the InputState class.
  120. inputState.Update();
  121. // Allows the game to exit
  122. if (inputState.PlayerExit(PlayerIndex.One))
  123. {
  124. this.Exit();
  125. }
  126. // If the player has only just pressed the Enter key or has pressed the Start button
  127. if (currentGameState == GameState.Loading)
  128. {
  129. if (inputState.StartGame(PlayerIndex.One))
  130. {
  131. ResetGame(gameTime, aspectRatio);
  132. }
  133. }
  134. // Main gameplay running screen
  135. if ((currentGameState == GameState.Running))
  136. {
  137. fuelCarrier.Update(inputState, barriers);
  138. float aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;
  139. gameCamera.Update(fuelCarrier.ForwardDirection, fuelCarrier.Position, aspectRatio);
  140. retrievedFuelCells = 0;
  141. foreach (FuelCell fuelCell in fuelCells)
  142. {
  143. fuelCell.Update(fuelCarrier.BoundingSphere);
  144. if (fuelCell.Retrieved)
  145. {
  146. retrievedFuelCells++;
  147. }
  148. }
  149. if (retrievedFuelCells == GameConstants.NumFuelCells)
  150. {
  151. currentGameState = GameState.Won;
  152. }
  153. roundTimer -= gameTime.ElapsedGameTime;
  154. if ((roundTimer < TimeSpan.Zero) && (retrievedFuelCells != GameConstants.NumFuelCells))
  155. {
  156. currentGameState = GameState.Lost;
  157. }
  158. }
  159. if ((currentGameState == GameState.Won) || (currentGameState == GameState.Lost))
  160. {
  161. // Gameplay has stopped and if audio is still playing, stop it.
  162. if (MediaPlayer.State == MediaState.Playing)
  163. {
  164. MediaPlayer.Stop();
  165. }
  166. // Reset the world for a new game
  167. if (inputState.StartGame(PlayerIndex.One))
  168. {
  169. ResetGame(gameTime, aspectRatio);
  170. }
  171. }
  172. base.Update(gameTime);
  173. }
  174. /// <summary>
  175. /// Draws the game from background to foreground.
  176. /// </summary>
  177. /// <param name="gameTime">Provides a snapshot of timing values.</param>
  178. protected override void Draw(GameTime gameTime)
  179. {
  180. GraphicsDevice.Clear(Color.Black);
  181. switch (currentGameState)
  182. {
  183. case GameState.Loading:
  184. DrawSplashScreen();
  185. break;
  186. case GameState.Running:
  187. DrawGameplayScreen();
  188. break;
  189. case GameState.Won:
  190. DrawWinOrLossScreen(GameConstants.StrGameWon);
  191. break;
  192. case GameState.Lost:
  193. DrawWinOrLossScreen(GameConstants.StrGameLost);
  194. break;
  195. };
  196. base.Draw(gameTime);
  197. }
  198. private void DrawGameplayScreen()
  199. {
  200. // Draw the ground terrain model
  201. DrawTerrain(ground.Model);
  202. // Draw the fuel cells on the map
  203. foreach (FuelCell fuelCell in fuelCells)
  204. {
  205. if (!fuelCell.Retrieved)
  206. {
  207. fuelCell.Draw(gameCamera.ViewMatrix, gameCamera.ProjectionMatrix);
  208. // Draw the bounding sphere for the fuel cells
  209. // ChangeRasterizerState(FillMode.WireFrame);
  210. // fuelCell.DrawBoundingSphere(gameCamera.ViewMatrix, gameCamera.ProjectionMatrix, boundingSphere);
  211. // ChangeRasterizerState(FillMode.Solid);
  212. }
  213. }
  214. // Draw the barriers on the map
  215. foreach (Barrier barrier in barriers)
  216. {
  217. barrier.Draw(gameCamera.ViewMatrix, gameCamera.ProjectionMatrix);
  218. // Draw the bounding sphere for the barriers
  219. // ChangeRasterizerState(FillMode.WireFrame);
  220. // barrier.DrawBoundingSphere(gameCamera.ViewMatrix, gameCamera.ProjectionMatrix, boundingSphere);
  221. // ChangeRasterizerState(FillMode.Solid);
  222. }
  223. // Draw the player fuelcarrier on the map
  224. fuelCarrier.Draw(gameCamera.ViewMatrix, gameCamera.ProjectionMatrix);
  225. // Draw the bounding sphere for the fuel carrier
  226. // ChangeRasterizerState(FillMode.WireFrame);
  227. // fuelCarrier.DrawBoundingSphere(gameCamera.ViewMatrix, gameCamera.ProjectionMatrix, boundingSphere);
  228. // ChangeRasterizerState(FillMode.Solid);
  229. DrawStats();
  230. }
  231. /// <summary>
  232. /// Helper function to change the rasterizer state for drawing the wireframe bounding spheres
  233. /// </summary>
  234. /// <param name="fillmode">The render `FillMode` to draw with, e.g. WireFrame</param>
  235. /// <param name="cullMode">The culling mode to draw with, e.g. None</param>
  236. /// <returns>Returns a new RasterizerState to apply to a graphics device</returns>
  237. private RasterizerState ChangeRasterizerState(FillMode fillmode, CullMode cullMode = CullMode.None)
  238. {
  239. RasterizerState rasterizerState = new RasterizerState()
  240. {
  241. FillMode = fillmode,
  242. CullMode = cullMode
  243. };
  244. graphics.GraphicsDevice.RasterizerState = rasterizerState;
  245. return rasterizerState;
  246. }
  247. private void DrawTerrain(Model model)
  248. {
  249. foreach (ModelMesh mesh in model.Meshes)
  250. {
  251. foreach (BasicEffect effect in mesh.Effects)
  252. {
  253. effect.EnableDefaultLighting();
  254. effect.PreferPerPixelLighting = true;
  255. effect.World = Matrix.Identity;
  256. // Use the matrices provided by the game camera
  257. effect.View = gameCamera.ViewMatrix;
  258. effect.Projection = gameCamera.ProjectionMatrix;
  259. }
  260. mesh.Draw();
  261. }
  262. }
  263. private void DrawSplashScreen()
  264. {
  265. float xOffsetText, yOffsetText;
  266. Vector2 viewportSize = new Vector2(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
  267. Vector2 strCenter;
  268. graphics.GraphicsDevice.Clear(Color.SteelBlue);
  269. xOffsetText = yOffsetText = 0;
  270. Vector2 strInstructionsSize = statsFont.MeasureString(GameConstants.StrInstructions1);
  271. Vector2 strPosition;
  272. strCenter = new Vector2(strInstructionsSize.X / 2, strInstructionsSize.Y / 2);
  273. yOffsetText = (viewportSize.Y / 2 - strCenter.Y);
  274. xOffsetText = (viewportSize.X / 2 - strCenter.X);
  275. strPosition = new Vector2(xOffsetText, yOffsetText);
  276. spriteBatch.Begin();
  277. spriteBatch.DrawString(statsFont, GameConstants.StrInstructions1, strPosition, Color.White);
  278. strInstructionsSize = statsFont.MeasureString(GameConstants.StrInstructions2);
  279. strCenter = new Vector2(strInstructionsSize.X / 2, strInstructionsSize.Y / 2);
  280. yOffsetText = (viewportSize.Y / 2 - strCenter.Y) + statsFont.LineSpacing;
  281. xOffsetText = (viewportSize.X / 2 - strCenter.X);
  282. strPosition = new Vector2(xOffsetText, yOffsetText);
  283. spriteBatch.DrawString(statsFont, GameConstants.StrInstructions2, strPosition, Color.LightGray);
  284. spriteBatch.End();
  285. ResetRenderStates();
  286. }
  287. private void DrawWinOrLossScreen(string gameResult)
  288. {
  289. float xOffsetText, yOffsetText;
  290. Vector2 viewportSize = new Vector2(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
  291. Vector2 strCenter;
  292. xOffsetText = yOffsetText = 0;
  293. Vector2 strResult = statsFont.MeasureString(gameResult);
  294. Vector2 strPlayAgainSize = statsFont.MeasureString(GameConstants.StrPlayAgain);
  295. Vector2 strPosition;
  296. strCenter = new Vector2(strResult.X / 2, strResult.Y / 2);
  297. yOffsetText = (viewportSize.Y / 2 - strCenter.Y);
  298. xOffsetText = (viewportSize.X / 2 - strCenter.X);
  299. strPosition = new Vector2(xOffsetText, yOffsetText);
  300. spriteBatch.Begin();
  301. spriteBatch.DrawString(statsFont, gameResult, strPosition, Color.Red);
  302. strCenter = new Vector2(strPlayAgainSize.X / 2, strPlayAgainSize.Y / 2);
  303. yOffsetText = (viewportSize.Y / 2 - strCenter.Y) + (float)statsFont.LineSpacing;
  304. xOffsetText = (viewportSize.X / 2 - strCenter.X);
  305. strPosition = new Vector2(xOffsetText, yOffsetText);
  306. spriteBatch.DrawString(statsFont, GameConstants.StrPlayAgain, strPosition, Color.AntiqueWhite);
  307. spriteBatch.End();
  308. ResetRenderStates();
  309. }
  310. private void DrawStats()
  311. {
  312. float xOffsetText, yOffsetText;
  313. string str1 = GameConstants.StrTimeRemaining;
  314. string str2 = GameConstants.StrCellsFound + retrievedFuelCells.ToString() + " of " + GameConstants.NumFuelCells.ToString();
  315. Rectangle rectSafeArea;
  316. str1 += (roundTimer.Seconds).ToString();
  317. //Calculate str1 position
  318. rectSafeArea = GraphicsDevice.Viewport.TitleSafeArea;
  319. xOffsetText = rectSafeArea.X;
  320. yOffsetText = rectSafeArea.Y;
  321. Vector2 strSize = statsFont.MeasureString(str1);
  322. Vector2 strPosition = new Vector2(xOffsetText + 10, yOffsetText);
  323. spriteBatch.Begin();
  324. spriteBatch.DrawString(statsFont, str1, strPosition, Color.White);
  325. strPosition.Y += strSize.Y;
  326. spriteBatch.DrawString(statsFont, str2, strPosition, Color.White);
  327. spriteBatch.End();
  328. ResetRenderStates();
  329. }
  330. private void ResetRenderStates()
  331. {
  332. //re-enable depth buffer after sprite batch disablement
  333. GraphicsDevice.DepthStencilState = DepthStencilState.Default;
  334. GraphicsDevice.BlendState = BlendState.Opaque;
  335. GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
  336. GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;
  337. }
  338. private void PlaceFuelCellsAndBarriers()
  339. {
  340. int min = GameConstants.MinDistance;
  341. int max = GameConstants.MaxDistance;
  342. Vector3 tempCenter;
  343. //place fuel cells
  344. foreach (FuelCell cell in fuelCells)
  345. {
  346. cell.Position = GenerateRandomPosition(min, max);
  347. tempCenter = cell.BoundingSphere.Center;
  348. tempCenter.X = cell.Position.X;
  349. tempCenter.Z = cell.Position.Z;
  350. cell.BoundingSphere = new BoundingSphere(tempCenter, cell.BoundingSphere.Radius);
  351. cell.Retrieved = false;
  352. }
  353. //place barriers
  354. foreach (Barrier barrier in barriers)
  355. {
  356. barrier.Position = GenerateRandomPosition(min, max);
  357. tempCenter = barrier.BoundingSphere.Center;
  358. tempCenter.X = barrier.Position.X;
  359. tempCenter.Z = barrier.Position.Z;
  360. barrier.BoundingSphere = new BoundingSphere(tempCenter, barrier.BoundingSphere.Radius);
  361. }
  362. }
  363. private Vector3 GenerateRandomPosition(int min, int max)
  364. {
  365. int xValue, zValue;
  366. do
  367. {
  368. xValue = random.Next(min, max);
  369. zValue = random.Next(min, max);
  370. if (random.Next(100) % 2 == 0)
  371. xValue *= -1;
  372. if (random.Next(100) % 2 == 0)
  373. zValue *= -1;
  374. } while (IsOccupied(xValue, zValue));
  375. return new Vector3(xValue, 0, zValue);
  376. }
  377. private bool IsOccupied(int xValue, int zValue)
  378. {
  379. foreach (GameObject currentObj in fuelCells)
  380. {
  381. if (((int)(MathHelper.Distance(xValue, currentObj.Position.X)) < 15) &&
  382. ((int)(MathHelper.Distance(zValue, currentObj.Position.Z)) < 15))
  383. {
  384. return true;
  385. }
  386. }
  387. foreach (GameObject currentObj in barriers)
  388. {
  389. if (((int)(MathHelper.Distance(xValue, currentObj.Position.X)) < 15) &&
  390. ((int)(MathHelper.Distance(zValue, currentObj.Position.Z)) < 15))
  391. {
  392. return true;
  393. }
  394. }
  395. return false;
  396. }
  397. private void ResetGame(GameTime gameTime, float aspectRatio)
  398. {
  399. fuelCarrier.Reset();
  400. gameCamera.Update(fuelCarrier.ForwardDirection, fuelCarrier.Position, aspectRatio);
  401. InitializeGameField();
  402. retrievedFuelCells = 0;
  403. startTime = gameTime.TotalGameTime;
  404. roundTimer = roundTime;
  405. currentGameState = GameState.Running;
  406. // We use a try catch around the Media player, else in debug mode it can cause an exception which we need to catch.
  407. try
  408. {
  409. MediaPlayer.Stop();
  410. MediaPlayer.IsRepeating = true;
  411. MediaPlayer.Volume = 0.5f;
  412. MediaPlayer.Play(backgroundMusic);
  413. }
  414. catch { }
  415. }
  416. private void InitializeGameField()
  417. {
  418. //Initialize barriers
  419. barriers = new Barrier[GameConstants.NumBarriers];
  420. int randomBarrier = random.Next(3);
  421. string barrierName = null;
  422. for (int index = 0; index < GameConstants.NumBarriers; index++)
  423. {
  424. switch (randomBarrier)
  425. {
  426. case 0:
  427. barrierName = "Models/cube10uR";
  428. break;
  429. case 1:
  430. barrierName = "Models/cylinder10uR";
  431. break;
  432. case 2:
  433. barrierName = "Models/pyramid10uR";
  434. break;
  435. }
  436. barriers[index] = new Barrier();
  437. barriers[index].LoadContent(Content, barrierName);
  438. randomBarrier = random.Next(3);
  439. }
  440. PlaceFuelCellsAndBarriers();
  441. }
  442. }
  443. }