Engine.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. using System;
  2. using System.IO;
  3. using Microsoft.Xna.Framework;
  4. using Microsoft.Xna.Framework.GamerServices;
  5. using Microsoft.Xna.Framework.Graphics;
  6. using Microsoft.Xna.Framework.Input;
  7. namespace Tetris
  8. {
  9. /// <summary>
  10. /// This is the main type for your game
  11. /// </summary>
  12. public class Engine : Microsoft.Xna.Framework.Game
  13. {
  14. // Graphics
  15. GraphicsDeviceManager graphics;
  16. SpriteBatch spriteBatch;
  17. Texture2D tetrisBackground, tetrisTextures;
  18. SpriteFont gameFont;
  19. readonly Rectangle[] blockRectangles = new Rectangle[7];
  20. // Game
  21. Board board;
  22. Score score;
  23. bool pause = false;
  24. // Input
  25. KeyboardState oldKeyboardState = Keyboard.GetState ();
  26. public Engine ()
  27. {
  28. graphics = new GraphicsDeviceManager (this);
  29. //Content.RootDirectory = "Content";
  30. Content.RootDirectory = "Content";
  31. // Create sprite rectangles for each figure in texture file
  32. // O figure
  33. blockRectangles [0] = new Rectangle (312, 0, 24, 24);
  34. // I figure
  35. blockRectangles [1] = new Rectangle (0, 24, 24, 24);
  36. // J figure
  37. blockRectangles [2] = new Rectangle (120, 0, 24, 24);
  38. // L figure
  39. blockRectangles [3] = new Rectangle (216, 24, 24, 24);
  40. // S figure
  41. blockRectangles [4] = new Rectangle (48, 96, 24, 24);
  42. // Z figure
  43. blockRectangles [5] = new Rectangle (240, 72, 24, 24);
  44. // T figure
  45. blockRectangles [6] = new Rectangle (144, 96, 24, 24);
  46. }
  47. /// <summary>
  48. /// Allows the game to perform any initialization it needs to before starting to run.
  49. /// This is where it can query for any required services and load any non-graphic
  50. /// related content. Calling base.Initialize will enumerate through any components
  51. /// and initialize them as well.
  52. /// </summary>
  53. protected override void Initialize ()
  54. {
  55. Window.Title = "MonoGame XNA Tetris 2D";
  56. graphics.PreferredBackBufferHeight = 600;
  57. graphics.PreferredBackBufferWidth = 800;
  58. graphics.ApplyChanges();
  59. this.TargetElapsedTime = TimeSpan.FromSeconds (1.0f / 10.0f);
  60. // Try to open file if it exists, otherwise create it
  61. using (FileStream fileStream = File.Open ("record.dat", FileMode.OpenOrCreate)) {
  62. fileStream.Close ();
  63. }
  64. base.Initialize ();
  65. }
  66. /// <summary>
  67. /// LoadContent will be called once per game and is the place to load
  68. /// all of your content.
  69. /// </summary>
  70. protected override void LoadContent ()
  71. {
  72. // Create a new SpriteBatch, which can be used to draw textures.
  73. spriteBatch = new SpriteBatch (GraphicsDevice);
  74. // Add the SpriteBatch service
  75. Services.AddService (typeof(SpriteBatch), spriteBatch);
  76. //Load 2D textures
  77. tetrisBackground = Content.Load<Texture2D> ("background");
  78. tetrisTextures = Content.Load<Texture2D> ("tetris");
  79. // Load game font
  80. //gameFont = Content.Load<SpriteFont> ("font");
  81. gameFont = Content.Load<SpriteFont> ("Arial");
  82. // Create game field
  83. board = new Board (this, ref tetrisTextures, blockRectangles);
  84. board.Initialize ();
  85. Components.Add (board);
  86. // Save player's score and game level
  87. score = new Score (this, gameFont);
  88. score.Initialize ();
  89. Components.Add (score);
  90. // Load game record
  91. using (StreamReader streamReader = File.OpenText ("record.dat")) {
  92. string player = null;
  93. if ((player = streamReader.ReadLine ()) != null)
  94. score.RecordPlayer = player;
  95. int record = 0;
  96. if ((record = Convert.ToInt32 (streamReader.ReadLine ())) != 0)
  97. score.RecordScore = record;
  98. }
  99. }
  100. /// <summary>
  101. /// Allows the game to run logic such as updating the world,
  102. /// checking for collisions, gathering input, and playing audio.
  103. /// </summary>
  104. /// <param name="gameTime">Provides a snapshot of timing values.</param>
  105. protected override void Update (GameTime gameTime)
  106. {
  107. // Allows the game to exit
  108. KeyboardState keyboardState = Keyboard.GetState ();
  109. if (keyboardState.IsKeyDown (Keys.Escape))
  110. this.Exit ();
  111. // Check pause
  112. bool pauseKey = (oldKeyboardState.IsKeyDown (Keys.P) && (keyboardState.IsKeyUp (Keys.P)));
  113. oldKeyboardState = keyboardState;
  114. if (pauseKey)
  115. pause = !pause;
  116. if (!pause) {
  117. // Find dynamic figure position
  118. board.FindDynamicFigure ();
  119. // Increase player score
  120. int lines = board.DestroyLines ();
  121. if (lines > 0) {
  122. score.Value += (int)((5.0f / 2.0f) * lines * (lines + 3));
  123. board.Speed += 0.005f;
  124. }
  125. score.Level = (int)(10 * board.Speed);
  126. // Create new shape in game
  127. if (!board.CreateNewFigure ())
  128. GameOver ();
  129. else {
  130. // If left key is pressed
  131. if (keyboardState.IsKeyDown (Keys.Left))
  132. board.MoveFigureLeft ();
  133. // If right key is pressed
  134. if (keyboardState.IsKeyDown (Keys.Right))
  135. board.MoveFigureRight ();
  136. // If down key is pressed
  137. if (keyboardState.IsKeyDown (Keys.Down))
  138. board.MoveFigureDown ();
  139. // Rotate figure
  140. if (keyboardState.IsKeyDown (Keys.Up) || keyboardState.IsKeyDown (Keys.Space))
  141. board.RotateFigure ();
  142. // Moving figure
  143. if (board.Movement >= 1) {
  144. board.Movement = 0;
  145. board.MoveFigureDown ();
  146. } else
  147. board.Movement += board.Speed;
  148. }
  149. }
  150. base.Update (gameTime);
  151. }
  152. private void GameOver ()
  153. {
  154. if (score.Value > score.RecordScore) {
  155. score.RecordScore = score.Value;
  156. pause = true;
  157. Record record = new Record ();
  158. //record.ShowDialog ();
  159. score.RecordPlayer = record.Player;
  160. using (StreamWriter writer = File.CreateText ("record.dat")) {
  161. writer.WriteLine (score.RecordPlayer);
  162. writer.WriteLine (score.RecordScore);
  163. }
  164. pause = false;
  165. }
  166. board.Initialize ();
  167. score.Initialize ();
  168. }
  169. /// <summary>
  170. /// This is called when the game should draw itself.
  171. /// </summary>
  172. /// <param name="gameTime">Provides a snapshot of timing values.</param>
  173. protected override void Draw (GameTime gameTime)
  174. {
  175. spriteBatch.Begin ();
  176. spriteBatch.Draw (tetrisBackground, Vector2.Zero, Color.White);
  177. base.Draw (gameTime);
  178. spriteBatch.End ();
  179. }
  180. }
  181. }