Advertisement
diliupg

GameProject_ProjInc5

Oct 27th, 2017
274
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.             for(int i = 0; i < GameConstants.MaxBears; i++)
  105.             {
  106.                 SpawnBear();
  107.             }
  108.  
  109.             // set initial health and score strings
  110.             healthString = GameConstants.HealthPrefix + GameConstants.BurgerInitialHealth;
  111.  
  112.             scoreString = GameConstants.ScorePrefix + 0;
  113.  
  114.         }
  115.  
  116.         /// <summary>
  117.         /// UnloadContent will be called once per game and is the place to unload
  118.         /// game-specific content.
  119.         /// </summary>
  120.         protected override void UnloadContent()
  121.         {
  122.             // TODO: Unload any non ContentManager content here
  123.         }
  124.  
  125.         /// <summary>
  126.         /// Allows the game to run logic such as updating the world,
  127.         /// checking for collisions, gathering input, and playing audio.
  128.         /// </summary>
  129.         /// <param name="gameTime">Provides a snapshot of timing values.</param>
  130.         protected override void Update(GameTime gameTime)
  131.         {
  132.             if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed ||
  133.                 Keyboard.GetState().IsKeyDown(Keys.Escape))
  134.                 Exit();
  135.  
  136.             // removed the mouse control and added keyboard control below
  137.  
  138.             // get current  state and update burger
  139.             //MouseState mouse = Mouse.GetState();
  140.             //burger.Update(gameTime, mouse);
  141.  
  142.             // get current keyboard state and update burger
  143.             KeyboardState keyboard = Keyboard.GetState();
  144.             burger.Update(gameTime, keyboard);
  145.  
  146.             // update other game objects
  147.             foreach (TeddyBear bear in bears)
  148.             {
  149.                 bear.Update(gameTime);
  150.             }
  151.             foreach (Projectile projectile in projectiles)
  152.             {
  153.                 projectile.Update(gameTime);
  154.             }
  155.             foreach (Explosion explosion in explosions)
  156.             {
  157.                 explosion.Update(gameTime);
  158.             }
  159.  
  160.             // check and resolve collisions between teddy bears
  161.             for (int i = 0; i < bears.Count; i++)
  162.             {
  163.                 for (int j = i + 1; j < bears.Count; j++)
  164.                 {
  165.                     if (bears[i].Active && bears[j].Active &&
  166.                         bears[i].CollisionRectangle.Intersects(bears[j].CollisionRectangle))
  167.                     {
  168.                         CollisionResolutionInfo collisionresult = CollisionUtils.CheckCollision
  169.                             (gameTime.ElapsedGameTime.Milliseconds,
  170.                             GameConstants.WindowWidth, GameConstants.WindowHeight,
  171.                             bears[i].Velocity, bears[i].DrawRectangle,
  172.                             bears[j].Velocity, bears[j].DrawRectangle);
  173.                         teddyBounce.Play(0.08f, 0, 0);
  174.  
  175.  
  176.                         if (collisionresult != null)
  177.                         {
  178.                             if (collisionresult.FirstOutOfBounds == true)
  179.                             {
  180.                                 bears[i].Active = false;
  181.                             }
  182.                             else
  183.                             {
  184.                                 bears[i].Velocity = collisionresult.FirstVelocity;
  185.                                 bears[i].DrawRectangle = collisionresult.FirstDrawRectangle;
  186.                             }
  187.                             if (collisionresult.SecondOutOfBounds == true)
  188.                             {
  189.                                 bears[j].Active = false;
  190.                             }
  191.                             else
  192.                             {
  193.                                 bears[j].Velocity = collisionresult.SecondVelocity;
  194.                                 bears[j].DrawRectangle = collisionresult.SecondDrawRectangle;
  195.                             }
  196.                         }
  197.                     }
  198.                 }
  199.             }
  200.             // check and resolve collisions between burger and teddy bears
  201.             foreach (TeddyBear bear in bears)
  202.             {
  203.                 if (bear.Active && burger.Health > 0 &&
  204.                     bear.CollisionRectangle.Intersects(burger.CollisionRectangle))
  205.                 {
  206.                     bear.Active = false;
  207.                     explosion.Play(.9f, 0, 0);
  208.                     explosions.Add(new Explosion(explosionSpriteStrip,
  209.                         bear.CollisionRectangle.Center.X, bear.CollisionRectangle.Center.Y));
  210.                     burger.Health -= GameConstants.BearDamage;
  211.                     CheckBurgerKill();
  212.                     burgerDamage.Play(.08f, 0, 0);
  213.  
  214.                 }
  215.             }
  216.             // check and resolve collisions between burger and projectiles
  217.             foreach(Projectile projectile in projectiles)
  218.             {
  219.                 if (projectile.Type == ProjectileType.TeddyBear &&
  220.                     projectile.Active && burger.Health > 0 &&
  221.                     projectile.CollisionRectangle.Intersects(burger.CollisionRectangle))
  222.                 {
  223.                     projectile.Active = false;
  224.                     burger.Health -= GameConstants.TeddyBearProjectileDamage;
  225.                     CheckBurgerKill();
  226.                     burgerDamage.Play(.08f, 0, 0);
  227.                 }
  228.  
  229.             }
  230.             // check and resolve collisions between teddy bears and projectiles
  231.             foreach (TeddyBear bear in bears)
  232.             {
  233.                 foreach (Projectile projectile in projectiles)
  234.                 {
  235.                     if (bear.Active && projectile.Active && projectile.Type == ProjectileType.FrenchFries &&
  236.                         bear.CollisionRectangle.Intersects(projectile.CollisionRectangle))
  237.                     {
  238.                         bear.Active = false;
  239.                         projectile.Active = false;
  240.                         explosion.Play(0.5f, -0.5f, 0);
  241.                         explosions.Add(new Explosion(explosionSpriteStrip,
  242.                         bear.CollisionRectangle.Center.X, bear.CollisionRectangle.Center.Y));
  243.  
  244.                         score += GameConstants.BearPoints;
  245.                     }
  246.                 }
  247.             }
  248.             if (burger.Health <= 0)
  249.             {
  250.                 burger.Health = 0;
  251.             }
  252.  
  253.             healthString = GameConstants.HealthPrefix + burger.Health;
  254.             scoreString = GameConstants.ScorePrefix + score;
  255.  
  256.             // clean out inactive teddy bears and add new ones as necessary
  257.             for (int i = bears.Count - 1; i >= 0; i--)
  258.             {
  259.                 if (!bears[i].Active)
  260.                 {
  261.                     bears.RemoveAt(i);
  262.                 }
  263.             }
  264.             // add new teddy bears to fill in for the ones reemoved
  265.  
  266.             while (bears.Count <= GameConstants.MaxBears-1)
  267.             {
  268.                 SpawnBear();
  269.             }
  270.             // clean out inactive projectiles
  271.             for (int i = projectiles.Count - 1; i >= 0; i--)
  272.             {
  273.                 if (!projectiles[i].Active)
  274.                 {
  275.                     projectiles.RemoveAt(i);
  276.                 }
  277.             }
  278.             // clean out finished explosions
  279.             for (int i = explosions.Count - 1; i >= 0; i--)
  280.             {
  281.                 if (explosions[i].Finished)
  282.                 {
  283.                     explosions.RemoveAt(i);
  284.                 }
  285.             }
  286.  
  287.             base.Update(gameTime);
  288.         }
  289.  
  290.         /// <summary>
  291.         /// This is called when the game should draw itself.
  292.         /// </summary>
  293.         /// <param name="gameTime">Provides a snapshot of timing values.</param>
  294.         protected override void Draw(GameTime gameTime)
  295.         {
  296.             GraphicsDevice.Clear(Color.CornflowerBlue);
  297.  
  298.             spriteBatch.Begin();
  299.  
  300.             // draw game objects
  301.             burger.Draw(spriteBatch);
  302.             foreach (TeddyBear bear in bears)
  303.             {
  304.                 bear.Draw(spriteBatch);
  305.             }
  306.             foreach (Projectile projectile in projectiles)
  307.             {
  308.                 projectile.Draw(spriteBatch);
  309.             }
  310.             foreach (Explosion explosion in explosions)
  311.             {
  312.                 explosion.Draw(spriteBatch);
  313.             }
  314.  
  315.             // draw score and health
  316.             spriteBatch.DrawString(font, healthString, GameConstants.HealthLocation, Color.White);
  317.  
  318.             spriteBatch.DrawString(font, scoreString, GameConstants.ScoreLocation, Color.White);
  319.  
  320.             spriteBatch.End();
  321.  
  322.             base.Draw(gameTime);
  323.         }
  324.  
  325.         #region Public methods
  326.  
  327.         /// <summary>
  328.         /// Gets the projectile sprite for the given projectile type
  329.         /// </summary>
  330.         /// <param name="type">the projectile type</param>
  331.         /// <returns>the projectile sprite for the type</returns>
  332.         public static Texture2D GetProjectileSprite(ProjectileType type)
  333.         {
  334.             // replace with code to return correct projectile sprite based on projectile type
  335.             if (type == ProjectileType.FrenchFries)
  336.             {
  337.                 return frenchFriesSprite;
  338.             }
  339.             else
  340.             {
  341.                 return teddyBearProjectileSprite;
  342.             }
  343.         }
  344.  
  345.         /// <summary>
  346.         /// Adds the given projectile to the game
  347.         /// </summary>
  348.         /// <param name="projectile">the projectile to add</param>
  349.         public static void AddProjectile(Projectile projectile)
  350.         {
  351.             projectiles.Add(projectile);
  352.         }
  353.  
  354.         #endregion
  355.  
  356.         #region Private methods
  357.  
  358.         /// <summary>
  359.         /// Spawns a new teddy bear at a random location
  360.         /// </summary>
  361.         private void SpawnBear()
  362.         {
  363.  
  364.             // generate random location
  365.             int bearPosX = GetRandomLocation(GameConstants.SpawnBorderSize,
  366.                 graphics.PreferredBackBufferWidth - GameConstants.SpawnBorderSize * 2);
  367.             int bearPosY = GetRandomLocation(GameConstants.SpawnBorderSize,
  368.                 graphics.PreferredBackBufferHeight - GameConstants.SpawnBorderSize * 2);
  369.  
  370.             // generate random velocity
  371.             float bearSpeed = GameConstants.MinBearSpeed +
  372.                 RandomNumberGenerator.NextFloat(GameConstants.BearSpeedRange);
  373.             float angle = RandomNumberGenerator.NextFloat(2 * (float)Math.PI);
  374.             Vector2 velocity = new Vector2
  375.                 ((float)(Math.Cos(angle) * bearSpeed), (float)(Math.Sin(angle) * bearSpeed));
  376.  
  377.             // create new bear
  378.             TeddyBear newBear = new TeddyBear(Content, @"graphics/teddybear", bearPosX,
  379.                 bearPosY, velocity, teddyBounce, teddyShot);
  380.  
  381.             // make sure we don't spawn into a collision
  382.             List<Rectangle> collist = new List<Rectangle>();
  383.             // get the existing bear collision rectangles into a list
  384.             foreach (TeddyBear bear in bears)
  385.             {
  386.                 collist.Add(bear.CollisionRectangle);
  387.             }
  388.             bool colloide = CollisionUtils.IsCollisionFree(newBear.CollisionRectangle, collist);
  389.             while (colloide == false)
  390.             {
  391.                 newBear.X = GetRandomLocation(GameConstants.SpawnBorderSize,
  392.                 graphics.PreferredBackBufferWidth - GameConstants.SpawnBorderSize * 2);
  393.  
  394.                 newBear.Y = GetRandomLocation(GameConstants.SpawnBorderSize,
  395.                 graphics.PreferredBackBufferHeight - GameConstants.SpawnBorderSize * 2);
  396.  
  397.                 colloide = CollisionUtils.IsCollisionFree(newBear.CollisionRectangle, collist);
  398.             }
  399.             // add new bear to list
  400.             bears.Add(newBear);
  401.         }
  402.  
  403.         /// <summary>
  404.         /// Gets a random location using the given min and range
  405.         /// </summary>
  406.         /// <param name="min">the minimum</param>
  407.         /// <param name="range">the range</param>
  408.         /// <returns>the random location</returns>
  409.         private int GetRandomLocation(int min, int range)
  410.         {
  411.             return min + RandomNumberGenerator.Next(range);
  412.         }
  413.  
  414.         /// <summary>
  415.         /// Gets a list of collision rectangles for all the objects in the game world
  416.         /// </summary>
  417.         /// <returns>the list of collision rectangles</returns>
  418.         private List<Rectangle> GetCollisionRectangles()
  419.         {
  420.             List<Rectangle> collisionRectangles = new List<Rectangle>();
  421.             collisionRectangles.Add(burger.CollisionRectangle);
  422.             foreach (TeddyBear bear in bears)
  423.             {
  424.                 collisionRectangles.Add(bear.CollisionRectangle);
  425.             }
  426.             foreach (Projectile projectile in projectiles)
  427.             {
  428.                 collisionRectangles.Add(projectile.CollisionRectangle);
  429.             }
  430.             foreach (Explosion explosion in explosions)
  431.             {
  432.                 collisionRectangles.Add(explosion.CollisionRectangle);
  433.             }
  434.             return collisionRectangles;
  435.         }
  436.         /// <summary>
  437.         /// Checks to see if the burger has just been killed
  438.         /// </summary>
  439.         private void CheckBurgerKill()
  440.         {
  441.             if (burger.Health <=0 && !burgerDead)
  442.             {
  443.                 burgerDead = true;
  444.                 burgerDeath.Play(1, 0, 0);
  445.             }
  446.  
  447.  
  448.         }
  449.  
  450.         #endregion
  451.     }
  452. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement