TetrisGame.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. using System;
  2. using System.IO;
  3. using Microsoft.Xna.Framework;
  4. // TODO 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 TetrisGame : 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 TetrisGame ()
  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 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. // Create game field
  82. board = new Board (this, ref tetrisTextures, blockRectangles);
  83. board.Initialize ();
  84. Components.Add (board);
  85. // Save player's score and game level
  86. score = new Score (this, gameFont);
  87. score.Initialize ();
  88. Components.Add (score);
  89. // Load game record
  90. using (StreamReader streamReader = File.OpenText ("record.dat")) {
  91. string player = null;
  92. if ((player = streamReader.ReadLine ()) != null)
  93. score.RecordPlayer = player;
  94. int record = 0;
  95. if ((record = Convert.ToInt32 (streamReader.ReadLine ())) != 0)
  96. score.RecordScore = record;
  97. }
  98. }
  99. /// <summary>
  100. /// Allows the game to run logic such as updating the world,
  101. /// checking for collisions, gathering input, and playing audio.
  102. /// </summary>
  103. /// <param name="gameTime">Provides a snapshot of timing values.</param>
  104. protected override void Update (GameTime gameTime)
  105. {
  106. // Allows the game to exit
  107. KeyboardState keyboardState = Keyboard.GetState ();
  108. if (keyboardState.IsKeyDown (Keys.Escape))
  109. this.Exit ();
  110. // Check pause
  111. bool pauseKey = (oldKeyboardState.IsKeyDown (Keys.P) && (keyboardState.IsKeyUp (Keys.P)));
  112. oldKeyboardState = keyboardState;
  113. if (pauseKey)
  114. pause = !pause;
  115. if (!pause) {
  116. // Find dynamic figure position
  117. board.FindDynamicFigure ();
  118. // Increase player score
  119. int lines = board.DestroyLines ();
  120. if (lines > 0) {
  121. score.Value += (int)((5.0f / 2.0f) * lines * (lines + 3));
  122. board.Speed += 0.005f;
  123. }
  124. score.Level = (int)(10 * board.Speed);
  125. // Create new shape in game
  126. if (!board.CreateNewFigure ())
  127. GameOver ();
  128. else {
  129. // If left key is pressed
  130. if (keyboardState.IsKeyDown (Keys.Left))
  131. board.MoveFigureLeft ();
  132. // If right key is pressed
  133. if (keyboardState.IsKeyDown (Keys.Right))
  134. board.MoveFigureRight ();
  135. // If down key is pressed
  136. if (keyboardState.IsKeyDown (Keys.Down))
  137. board.MoveFigureDown ();
  138. // Rotate figure
  139. if (keyboardState.IsKeyDown (Keys.Up) || keyboardState.IsKeyDown (Keys.Space))
  140. board.RotateFigure ();
  141. // Moving figure
  142. if (board.Movement >= 1) {
  143. board.Movement = 0;
  144. board.MoveFigureDown ();
  145. } else
  146. board.Movement += board.Speed;
  147. }
  148. }
  149. base.Update (gameTime);
  150. }
  151. private void GameOver ()
  152. {
  153. if (score.Value > score.RecordScore) {
  154. score.RecordScore = score.Value;
  155. pause = true;
  156. Record record = new Record ();
  157. //record.ShowDialog ();
  158. score.RecordPlayer = record.Player;
  159. using (StreamWriter writer = File.CreateText ("record.dat")) {
  160. writer.WriteLine (score.RecordPlayer);
  161. writer.WriteLine (score.RecordScore);
  162. }
  163. pause = false;
  164. }
  165. board.Initialize ();
  166. score.Initialize ();
  167. }
  168. /// <summary>
  169. /// This is called when the game should draw itself.
  170. /// </summary>
  171. /// <param name="gameTime">Provides a snapshot of timing values.</param>
  172. protected override void Draw (GameTime gameTime)
  173. {
  174. spriteBatch.Begin ();
  175. spriteBatch.Draw (tetrisBackground, Vector2.Zero, Color.White);
  176. base.Draw (gameTime);
  177. spriteBatch.End ();
  178. }
  179. }
  180. }