Advertisement
diliupg

Game1.cs from Game Project

Nov 11th, 2017
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 17.10 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. using Microsoft.Xna.Framework;
  5. using Microsoft.Xna.Framework.Audio;
  6. using Microsoft.Xna.Framework.Graphics;
  7. using Microsoft.Xna.Framework.Input;
  8.  
  9. namespace GameProject
  10. {
  11.     /// <summary>
  12.     /// This is the main type for your game.
  13.     /// </summary>
  14.     public class Game1 : Game
  15.     {
  16.         GraphicsDeviceManager graphics;
  17.         SpriteBatch spriteBatch;
  18.  
  19.         // game objects. Using inheritance would make this easier,
  20.         //but inheritance isn't a GDD 1200 topic
  21.         Burger burger;
  22.         List<TeddyBear> bears = new List<TeddyBear>();
  23.         static List<Projectile> projectiles = new List<Projectile>();
  24.         List<Explosion> explosions = new List<Explosion>();
  25.  
  26.         // projectile and explosion sprites.
  27.         //Saved so they don't have to be loaded every time projectiles or explosions are created
  28.         static Texture2D frenchFriesSprite;
  29.         static Texture2D teddyBearProjectileSprite;
  30.         static Texture2D explosionSpriteStrip;
  31.  
  32.         // scoring support
  33.         int score = 0;
  34.         string scoreString;
  35.         // health support
  36.         string healthString = GameConstants.HealthPrefix + 0;
  37.  
  38.         bool burgerDead = false;
  39.  
  40.         // text display support
  41.         SpriteFont font;
  42.  
  43.         // sound effects
  44.         SoundEffect burgerDamage;
  45.         SoundEffect burgerDeath;
  46.         SoundEffect burgerShot;
  47.         SoundEffect explosion;
  48.         SoundEffect teddyBounce;
  49.         SoundEffect teddyShot;
  50.  
  51.         public Game1()
  52.         {
  53.             graphics = new GraphicsDeviceManager(this);
  54.             Content.RootDirectory = "Content";
  55.  
  56.             // set resolution
  57.             graphics.PreferredBackBufferWidth = GameConstants.WindowWidth;
  58.             graphics.PreferredBackBufferHeight = GameConstants.WindowHeight;
  59.         }
  60.  
  61.         /// <summary>
  62.         /// Allows the game to perform any initialization it needs to before starting to run.
  63.         /// This is where it can query for any required services and load any non-graphic
  64.         /// related content.  Calling base.Initialize will enumerate through any components
  65.         /// and initialize them as well.
  66.         /// </summary>
  67.         protected override void Initialize()
  68.         {
  69.             RandomNumberGenerator.Initialize();
  70.  
  71.             base.Initialize();
  72.         }
  73.  
  74.         /// <summary>
  75.         /// LoadContent will be called once per game and is the place to load
  76.         /// all of your content.
  77.         /// </summary>
  78.         protected override void LoadContent()
  79.         {
  80.             // Create a new SpriteBatch, which can be used to draw textures.
  81.             spriteBatch = new SpriteBatch(GraphicsDevice);
  82.  
  83.             // load audio content
  84.             burgerDamage = Content.Load<SoundEffect>(@"audio/BurgerDamage");
  85.             burgerDeath = Content.Load<SoundEffect>(@"audio/BurgerDeath");
  86.             burgerShot = Content.Load<SoundEffect>(@"audio/BurgerShot");
  87.             explosion = Content.Load<SoundEffect>(@"audio/Explosion");
  88.             teddyBounce = Content.Load<SoundEffect>(@"audio/TeddyBounce");
  89.             teddyShot = Content.Load<SoundEffect>(@"audio/TeddyShot");
  90.  
  91.  
  92.             // load sprite font
  93.             font = Content.Load<SpriteFont>(@"fonts/Arial20");
  94.             // load projectile and explosion sprites
  95.             teddyBearProjectileSprite = Content.Load<Texture2D>(@"graphics/teddybearprojectile");
  96.             frenchFriesSprite = Content.Load<Texture2D>(@"graphics/frenchfries");
  97.             explosionSpriteStrip = Content.Load<Texture2D>(@"graphics/explosion");
  98.  
  99.             // add initial game objects
  100.             burger = new Burger(Content, (@"graphics/burger"),
  101.                 graphics.PreferredBackBufferWidth / 2,
  102.                 graphics.PreferredBackBufferHeight - graphics.PreferredBackBufferHeight / 8,
  103.                 burgerShot);
  104.  
  105.             for(int i = 0; i < GameConstants.MaxBears; i++)
  106.             {
  107.                 SpawnBear();
  108.             }
  109.  
  110.             // set initial health and score strings
  111.             healthString = GameConstants.HealthPrefix + GameConstants.BurgerInitialHealth;
  112.  
  113.             scoreString = GameConstants.ScorePrefix + 0;
  114.  
  115.         }
  116.  
  117.         /// <summary>
  118.         /// UnloadContent will be called once per game and is the place to unload
  119.         /// game-specific content.
  120.         /// </summary>
  121.         protected override void UnloadContent()
  122.         {
  123.             // TODO: Unload any non ContentManager content here
  124.         }
  125.  
  126.         /// <summary>
  127.         /// Allows the game to run logic such as updating the world,
  128.         /// checking for collisions, gathering input, and playing audio.
  129.         /// </summary>
  130.         /// <param name="gameTime">Provides a snapshot of timing values.</param>
  131.         protected override void Update(GameTime gameTime)
  132.         {
  133.             if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed ||
  134.                 Keyboard.GetState().IsKeyDown(Keys.Escape))
  135.                 Exit();
  136.  
  137.             // removed the mouse control and added keyboard control below
  138.  
  139.             // get current  state and update burger
  140.             //MouseState mouse = Mouse.GetState();
  141.             //burger.Update(gameTime, mouse);
  142.  
  143.             // get current keyboard state and update burger
  144.             KeyboardState keyboard = Keyboard.GetState();
  145.             burger.Update(gameTime, keyboard);
  146.  
  147.             // update other game objects
  148.             foreach (TeddyBear bear in bears)
  149.             {
  150.                 bear.Update(gameTime);
  151.             }
  152.             foreach (Projectile projectile in projectiles)
  153.             {
  154.                 projectile.Update(gameTime);
  155.             }
  156.             foreach (Explosion explosion in explosions)
  157.             {
  158.                 explosion.Update(gameTime);
  159.             }
  160.  
  161.             // check and resolve collisions between teddy bears
  162.             for (int i = 0; i < bears.Count; i++)
  163.             {
  164.                 for (int j = i + 1; j < bears.Count; j++)
  165.                 {
  166.                     if (bears[i].Active && bears[j].Active &&
  167.                         bears[i].CollisionRectangle.Intersects(bears[j].CollisionRectangle))
  168.                     {
  169.                         CollisionResolutionInfo collisionresult = CollisionUtils.CheckCollision
  170.                             (gameTime.ElapsedGameTime.Milliseconds,
  171.                             GameConstants.WindowWidth, GameConstants.WindowHeight,
  172.                             bears[i].Velocity, bears[i].DrawRectangle,
  173.                             bears[j].Velocity, bears[j].DrawRectangle);
  174.                         teddyBounce.Play(0.08f, 0, 0);
  175.  
  176.  
  177.                         if (collisionresult != null)
  178.                         {
  179.                             if (collisionresult.FirstOutOfBounds == true)
  180.                             {
  181.                                 bears[i].Active = false;
  182.                             }
  183.                             else
  184.                             {
  185.                                 bears[i].Velocity = collisionresult.FirstVelocity;
  186.                                 bears[i].DrawRectangle = collisionresult.FirstDrawRectangle;
  187.                             }
  188.                             if (collisionresult.SecondOutOfBounds == true)
  189.                             {
  190.                                 bears[j].Active = false;
  191.                             }
  192.                             else
  193.                             {
  194.                                 bears[j].Velocity = collisionresult.SecondVelocity;
  195.                                 bears[j].DrawRectangle = collisionresult.SecondDrawRectangle;
  196.                             }
  197.                         }
  198.                     }
  199.                 }
  200.             }
  201.             // check and resolve collisions between burger and teddy bears
  202.             foreach (TeddyBear bear in bears)
  203.             {
  204.                 if (bear.Active && burger.Health > 0 &&
  205.                     bear.CollisionRectangle.Intersects(burger.CollisionRectangle))
  206.                 {
  207.                     bear.Active = false;
  208.                     explosion.Play(.9f, 0, 0);
  209.                     explosions.Add(new Explosion(explosionSpriteStrip,
  210.                         bear.CollisionRectangle.Center.X, bear.CollisionRectangle.Center.Y));
  211.                     burger.Health -= GameConstants.BearDamage;
  212.                     CheckBurgerKill();
  213.                     burgerDamage.Play(.08f, 0, 0);
  214.  
  215.                 }
  216.             }
  217.             // check and resolve collisions between burger and projectiles
  218.             foreach(Projectile projectile in projectiles)
  219.             {
  220.                 if (projectile.Type == ProjectileType.TeddyBear &&
  221.                     projectile.Active && burger.Health > 0 &&
  222.                     projectile.CollisionRectangle.Intersects(burger.CollisionRectangle))
  223.                 {
  224.                     projectile.Active = false;
  225.                     burger.Health -= GameConstants.TeddyBearProjectileDamage;
  226.                     CheckBurgerKill();
  227.                     burgerDamage.Play(.08f, 0, 0);
  228.                 }
  229.  
  230.             }
  231.             // check and resolve collisions between teddy bears and projectiles
  232.             foreach (TeddyBear bear in bears)
  233.             {
  234.                 foreach (Projectile projectile in projectiles)
  235.                 {
  236.                     if (bear.Active && projectile.Active && projectile.Type == ProjectileType.FrenchFries &&
  237.                         bear.CollisionRectangle.Intersects(projectile.CollisionRectangle))
  238.                     {
  239.                         bear.Active = false;
  240.                         projectile.Active = false;
  241.                         explosion.Play(0.5f, -0.5f, 0);
  242.                         explosions.Add(new Explosion(explosionSpriteStrip,
  243.                         bear.CollisionRectangle.Center.X, bear.CollisionRectangle.Center.Y));
  244.  
  245.                         score += GameConstants.BearPoints;
  246.                     }
  247.                 }
  248.             }
  249.             if (burger.Health <= 0)
  250.             {
  251.                 burger.Health = 0;
  252.             }
  253.  
  254.             healthString = GameConstants.HealthPrefix + burger.Health;
  255.             scoreString = GameConstants.ScorePrefix + score;
  256.  
  257.             // clean out inactive teddy bears and add new ones as necessary
  258.             for (int i = bears.Count - 1; i >= 0; i--)
  259.             {
  260.                 if (!bears[i].Active)
  261.                 {
  262.                     bears.RemoveAt(i);
  263.                 }
  264.             }
  265.             // add new teddy bears to fill in for the ones reemoved
  266.  
  267.             while (bears.Count <= GameConstants.MaxBears-1)
  268.             {
  269.                 SpawnBear();
  270.             }
  271.             // clean out inactive projectiles
  272.             for (int i = projectiles.Count - 1; i >= 0; i--)
  273.             {
  274.                 if (!projectiles[i].Active)
  275.                 {
  276.                     projectiles.RemoveAt(i);
  277.                 }
  278.             }
  279.             // clean out finished explosions
  280.             for (int i = explosions.Count - 1; i >= 0; i--)
  281.             {
  282.                 if (explosions[i].Finished)
  283.                 {
  284.                     explosions.RemoveAt(i);
  285.                 }
  286.             }
  287.  
  288.             base.Update(gameTime);
  289.         }
  290.  
  291.         /// <summary>
  292.         /// This is called when the game should draw itself.
  293.         /// </summary>
  294.         /// <param name="gameTime">Provides a snapshot of timing values.</param>
  295.         protected override void Draw(GameTime gameTime)
  296.         {
  297.             GraphicsDevice.Clear(Color.CornflowerBlue);
  298.  
  299.             spriteBatch.Begin();
  300.  
  301.             // draw game objects
  302.             burger.Draw(spriteBatch);
  303.             foreach (TeddyBear bear in bears)
  304.             {
  305.                 bear.Draw(spriteBatch);
  306.             }
  307.             foreach (Projectile projectile in projectiles)
  308.             {
  309.                 projectile.Draw(spriteBatch);
  310.             }
  311.             foreach (Explosion explosion in explosions)
  312.             {
  313.                 explosion.Draw(spriteBatch);
  314.             }
  315.  
  316.             // draw score and health
  317.             spriteBatch.DrawString(font, healthString, GameConstants.HealthLocation, Color.White);
  318.  
  319.             spriteBatch.DrawString(font, scoreString, GameConstants.ScoreLocation, Color.White);
  320.  
  321.             spriteBatch.End();
  322.  
  323.             base.Draw(gameTime);
  324.         }
  325.  
  326.         #region Public methods
  327.  
  328.         /// <summary>
  329.         /// Gets the projectile sprite for the given projectile type
  330.         /// </summary>
  331.         /// <param name="type">the projectile type</param>
  332.         /// <returns>the projectile sprite for the type</returns>
  333.         public static Texture2D GetProjectileSprite(ProjectileType type)
  334.         {
  335.             // replace with code to return correct projectile sprite based on projectile type
  336.             if (type == ProjectileType.FrenchFries)
  337.             {
  338.                 return frenchFriesSprite;
  339.             }
  340.             else
  341.             {
  342.                 return teddyBearProjectileSprite;
  343.             }
  344.         }
  345.  
  346.         /// <summary>
  347.         /// Adds the given projectile to the game
  348.         /// </summary>
  349.         /// <param name="projectile">the projectile to add</param>
  350.         public static void AddProjectile(Projectile projectile)
  351.         {
  352.             projectiles.Add(projectile);
  353.         }
  354.  
  355.         #endregion
  356.  
  357.         #region Private methods
  358.  
  359.         /// <summary>
  360.         /// Spawns a new teddy bear at a random location
  361.         /// </summary>
  362.         private void SpawnBear()
  363.         {
  364.  
  365.             // generate random location
  366.             int bearPosX = GetRandomLocation(GameConstants.SpawnBorderSize,
  367.                 graphics.PreferredBackBufferWidth - GameConstants.SpawnBorderSize * 2);
  368.             int bearPosY = GetRandomLocation(GameConstants.SpawnBorderSize,
  369.                 graphics.PreferredBackBufferHeight - GameConstants.SpawnBorderSize * 2);
  370.  
  371.             // generate random velocity
  372.             float bearSpeed = GameConstants.MinBearSpeed +
  373.                 RandomNumberGenerator.NextFloat(GameConstants.BearSpeedRange);
  374.             float angle = RandomNumberGenerator.NextFloat(2 * (float)Math.PI);
  375.             Vector2 velocity = new Vector2
  376.                 ((float)(Math.Cos(angle) * bearSpeed), (float)(Math.Sin(angle) * bearSpeed));
  377.  
  378.             // create new bear
  379.             TeddyBear newBear = new TeddyBear(Content, @"graphics/teddybear", bearPosX,
  380.                 bearPosY, velocity, teddyBounce, teddyShot);
  381.  
  382.             // make sure we don't spawn into a collision
  383.             List<Rectangle> collist = new List<Rectangle>();
  384.             // get the existing bear collision rectangles into a list
  385.             foreach (TeddyBear bear in bears)
  386.             {
  387.                 collist.Add(bear.CollisionRectangle);
  388.             }
  389.             bool colloide = CollisionUtils.IsCollisionFree(newBear.CollisionRectangle, collist);
  390.             while (colloide == false)
  391.             {
  392.                 newBear.X = GetRandomLocation(GameConstants.SpawnBorderSize,
  393.                 graphics.PreferredBackBufferWidth - GameConstants.SpawnBorderSize * 2);
  394.  
  395.                 newBear.Y = GetRandomLocation(GameConstants.SpawnBorderSize,
  396.                 graphics.PreferredBackBufferHeight - GameConstants.SpawnBorderSize * 2);
  397.  
  398.                 colloide = CollisionUtils.IsCollisionFree(newBear.CollisionRectangle, collist);
  399.             }
  400.             // add new bear to list
  401.             bears.Add(newBear);
  402.         }
  403.  
  404.         /// <summary>
  405.         /// Gets a random location using the given min and range
  406.         /// </summary>
  407.         /// <param name="min">the minimum</param>
  408.         /// <param name="range">the range</param>
  409.         /// <returns>the random location</returns>
  410.         private int GetRandomLocation(int min, int range)
  411.         {
  412.             return min + RandomNumberGenerator.Next(range);
  413.         }
  414.  
  415.         /// <summary>
  416.         /// Gets a list of collision rectangles for all the objects in the game world
  417.         /// </summary>
  418.         /// <returns>the list of collision rectangles</returns>
  419.         private List<Rectangle> GetCollisionRectangles()
  420.         {
  421.             List<Rectangle> collisionRectangles = new List<Rectangle>();
  422.             collisionRectangles.Add(burger.CollisionRectangle);
  423.             foreach (TeddyBear bear in bears)
  424.             {
  425.                 collisionRectangles.Add(bear.CollisionRectangle);
  426.             }
  427.             foreach (Projectile projectile in projectiles)
  428.             {
  429.                 collisionRectangles.Add(projectile.CollisionRectangle);
  430.             }
  431.             foreach (Explosion explosion in explosions)
  432.             {
  433.                 collisionRectangles.Add(explosion.CollisionRectangle);
  434.             }
  435.             return collisionRectangles;
  436.         }
  437.         /// <summary>
  438.         /// Checks to see if the burger has just been killed
  439.         /// </summary>
  440.         private void CheckBurgerKill()
  441.         {
  442.             if (burger.Health <=0 && !burgerDead)
  443.             {
  444.                 burgerDead = true;
  445.                 burgerDeath.Play(1, 0, 0);
  446.             }
  447.  
  448.  
  449.         }
  450.  
  451.         #endregion
  452.     }
  453. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement