LoadingScreen.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //-----------------------------------------------------------------------------
  2. // LoadingScreen.cs
  3. //
  4. // Display a screen to inform the player that their game is still responding,
  5. // while loading content in the background.
  6. //-----------------------------------------------------------------------------
  7. using Microsoft.Xna.Framework;
  8. using Microsoft.Xna.Framework.Graphics;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Text;
  12. using System.Threading;
  13. using RacingGame.Graphics;
  14. using System.Threading.Tasks;
  15. using RacingGame.Helpers;
  16. namespace RacingGame.GameScreens
  17. {
  18. /// <summary>
  19. /// Loading screen
  20. /// </summary>
  21. class LoadingScreen : IGameScreen
  22. {
  23. private const string loadingText = "Loading...";
  24. private int loadingTextWidth = TextureFont.GetTextWidth(loadingText);
  25. private string loadingStatus = "";
  26. public LoadingScreen()
  27. {
  28. //Setup the handler before we start the thread
  29. RacingGameManager.LoadEvent += new EventHandler<EventArgs>(LoadEvent);
  30. }
  31. /// <summary>
  32. /// Gather input on the loading screen and update it if progress has
  33. /// changed in loading the game.
  34. /// </summary>
  35. public void Update(GameTime gameTime)
  36. {
  37. if (RacingGameManager.LoadingTask == null)
  38. {
  39. RacingGameManager.LoadingTask = Task.Run(() =>
  40. RacingGameManager.LoadResources());
  41. }
  42. if (RacingGameManager.LoadingTask.IsCompleted)
  43. {
  44. if (RacingGameManager.LoadingTask.IsFaulted)
  45. {
  46. Log.Write("Content loading failed: " +
  47. RacingGameManager.LoadingTask.Exception);
  48. }
  49. // Proceed to next screen
  50. }
  51. }
  52. public void LoadEvent(object sender, EventArgs e)
  53. {
  54. loadingStatus = (string)sender;
  55. }
  56. /// <summary>
  57. /// Render loading screen
  58. /// </summary>
  59. public bool Render()
  60. {
  61. SpriteBatch textBatch = new SpriteBatch(BaseGame.Device);
  62. Vector2 position = new Vector2((BaseGame.Width / 2) - 50, (BaseGame.Height / 2) - 20);
  63. for (int i = 0; i < loadingText.Length; i++)
  64. {
  65. string charStr = new string(loadingText[i], 1);
  66. int charHeight = (int)(position.Y + 7 * Math.Abs(Math.Sin((i / 4f) + (-BaseGame.TotalTime * 3))));
  67. TextureFont.WriteText((int)position.X, charHeight, charStr, Color.Red);
  68. position.X += TextureFont.GetTextWidth(charStr);
  69. }
  70. TextureFont.WriteTextCentered(BaseGame.Width / 2, (int)position.Y + 40, loadingStatus);
  71. return RacingGameManager.ContentLoaded;
  72. }
  73. }
  74. }