Cxna Gamecode Ex1
Cxna Gamecode Ex1
System; System.Collections.Generic; System.Linq; Microsoft.Xna.Framework; Microsoft.Xna.Framework.Audio; Microsoft.Xna.Framework.Content; Microsoft.Xna.Framework.GamerServices; Microsoft.Xna.Framework.Graphics; Microsoft.Xna.Framework.Input; Microsoft.Xna.Framework.Media;
using Collisions; namespace OptionalProject { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; // game objects. Burger burger; List<TeddyBear> bears = new List<TeddyBear>(); static List<Projectile> projectiles = new List<Projectile>(); List<Explosion> explosions = new List<Explosion>(); // projectile and explosion sprites. Saved so they don't have to // be loaded every time projectiles or explosions are created static Texture2D frenchFriesSprite; static Texture2D teddyBearProjectileSprite; static Texture2D explosionSpriteStrip; // spawn location support const int SPAWN_BORDER_SIZE = 100; // scoring support int score = 0; string scoreString = GameConstants.SCORE_PREFIX + 0; // health support string healthString = GameConstants.HEALTH_PREFIX + GameConstants.BURGER_INITIAL_HEALTH; bool burgerDead = false; // text display support SpriteFont font; // audio components AudioEngine audioEngine; WaveBank waveBank; SoundBank soundBank; //burger support Vector2 velocity;
public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.PreferredBackBufferWidth = GameConstants.WINDOW_WIDTH; graphics.PreferredBackBufferHeight = GameConstants.WINDOW_HEIGHT; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { RandomNumberGenerator.Initialize(); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); burger = new Burger(Content, "burger", graphics.PreferredBackBufferWidth / 2, graphics.PreferredBackBufferHeight * 3 / 4); // load audio audioEngine = waveBank = soundBank = content new AudioEngine(@"Content\GameAudio.xgs"); new WaveBank(audioEngine, @"Content\Wave Bank.xwb"); new SoundBank(audioEngine, @"Content\Sound Bank.xsb");
// load sprite font font = Content.Load<SpriteFont>("Arial20"); // load projectile and explosion sprites teddyBearProjectileSprite = Content.Load<Texture2D>("teddybearprojectile"); frenchFriesSprite = Content.Load<Texture2D>("frenchfries"); explosionSpriteStrip = Content.Load<Texture2D>("explosion"); // add initial game objects for( int i = 0; i < GameConstants.MAX_BEARS; i++) { SpawnBear(); } } /// <summary> /// UnloadContent will be called once per game and is the place to unload
/// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Get state of the keyboard KeyboardState keyboard = Keyboard.GetState(); // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) this.Exit(); // update burger burger.Update(gameTime, keyboard, soundBank); // update other game objects foreach (TeddyBear bear in bears) { // if bear isActive then update if (bear.IsActive) { bear.Update(gameTime, soundBank); } } foreach (Projectile projectile in projectiles) { projectile.Update(gameTime); } foreach (Explosion explosion in explosions) { explosion.Update(gameTime); } // check and resolve collisions between teddy bears for (int i = 0; i < bears.Count; i++) { for (int j = i + 1; j < bears.Count; j++) { CollisionResolutionInfo collisionRes = CollisionUtils.CheckCollision( 60, GameConstants.WINDOW_WIDTH, GameConstants.WINDOW_HEIGHT, bears[i].Velocity, bears[i].DrawRectangle, bears[j].Velocity, bears[j].DrawRectangle); if (collisionRes != null) { if (collisionRes.FirstOutOfBounds) { bears[j].IsActive = false;
} else { bears[j].Velocity = collisionRes.FirstVelocity; bears[j].DrawRectangle = collisionRes.FirstDrawRectangle; } if (collisionRes.SecondOutOfBounds) { bears[i].IsActive = false; } else { bears[i].Velocity = collisionRes.SecondVelocity; bears[i].DrawRectangle = collisionRes.SecondDrawRectangle; } } } } // check and resolve collisions between burger and teddy bears foreach (TeddyBear bear in bears) { // check if burger and teddy bear collide if (bear.CollisionRectangle.Intersects(burger.CollisionRectangle)) { // if collision, subtract health from burger burger.Health -= GameConstants.BEAR_DAMAGE; //CheckBurgerKill when burger takes damage CheckBurgerKill(); // set bear isActive to false bear.IsActive = false; //add explosion when burger hits bear Explosion explosion = new Explosion(explosionSpriteStrip, bear.Location.X, bear.Location.Y); //add explosion to explosions list explosions.Add(explosion); //play Explosion whenever a new Explosion is created soundBank.PlayCue("Explosion"); //play BurgerDamage when burger takes damage from colliding with teddy bear soundBank.PlayCue("BurgerDamage"); } } //check and resolve collisions between burger and projectiles foreach (Projectile projectile in projectiles) { //check for current teddy bear projectile and burger collision if (projectile.CollisionRectangle.Intersects(burger.CollisionRectangle) && projectile.Type == ProjectileType.TeddyBear ) {
// set projectile to inactive projectile.IsActive = false; //add explosion when teddybear projectile hits burger Explosion explosion = new Explosion(explosionSpriteStrip, burger.CollisionRectangle.X, burger.CollisionRectangle.Y); //add explosion to explosions list explosions.Add(explosion); //decrease burger health by teddy bear projectile damage burger.Health -= GameConstants.TEDDY_BEAR_PROJECTILE_DAMAGE; //CheckBurgerKill when burger takes damage to see if game over CheckBurgerKill(); //play BurgerDamage when burger takes damage from colliding with teddy bear projectile soundBank.PlayCue("BurgerDamage"); } } // check and resolve collisions between teddy bears and projectiles foreach (TeddyBear bear in bears) { foreach (Projectile projectile in projectiles) { if (bear.CollisionRectangle.Intersects(projectile.CollisionRectangle) && projectile.Type == ProjectileType.FrenchFries) { //make bear and projectile in collision both inactive bear.IsActive = false; projectile.IsActive = false; //add explosion when fries hit bear Explosion explosion = new Explosion(explosionSpriteStrip, bear.Location.X, bear.Location.Y); //add explosion to explosions list explosions.Add(explosion); //play Explosion whenever a new Explosion is created soundBank.PlayCue("Explosion"); //add points to score score += GameConstants.FRENCH_FRIES_PROJECTILE_DAMAGE; scoreString = GameConstants.SCORE_PREFIX + score; } } } // Check and resolve collisions between burger projectiles and bear projectiles foreach (Projectile friesProjectile in projectiles) { foreach (Projectile bearProjectile in projectiles) {
// check for bear projectile and burger projectile collision if (friesProjectile.CollisionRectangle.Intersects(bearProjectile.CollisionRectangle) && bearProjectile.Type == ProjectileType.TeddyBear && friesProjectile.Type == ProjectileType.FrenchFries) { // set projectile isActive to false bearProjectile.IsActive = false; friesProjectile.IsActive = false; //add explosion when fries hit bear Explosion explosion = new Explosion(explosionSpriteStrip, bearProjectile.CollisionRectangle.X, bearProjectile.CollisionRectangle.Y); //add explosion to explosions list explosions.Add(explosion); //play Explosion whenever a new Explosion is created soundBank.PlayCue("Explosion"); //add points to score score += GameConstants.FRENCH_FRIES_PROJECTILE_DAMAGE; scoreString = GameConstants.SCORE_PREFIX + score; } } } // clean out inactive teddy bears and add new ones as necessary for (int i = bears.Count - 1; i >= 0; i--) { // if bear is not active if (!bears[i].IsActive) { // remove bears bears.RemoveAt(i); } } // while number of bears is less than max number of bears while (bears.Count < GameConstants.MAX_BEARS) { // spawn new bear SpawnBear(); } // clean out inactive projectiles for (int i = projectiles.Count - 1; i >= 0; i--) { // remove projectiles if inactive if (!projectiles[i].IsActive) { projectiles.RemoveAt(i); } } // clean out finished explosions for (int i = explosions.Count - 1; i >= 0; i--) {
if (explosions[i].Finished) { explosions.RemoveAt(i); } } // set the healthString variable to the GameConstants HEALTH_PREFIX constant // concatenated with the current burger health healthString = GameConstants.HEALTH_PREFIX + burger.Health; base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); // draw game objects burger.Draw(spriteBatch); foreach (TeddyBear bear in bears) { if (bear.IsActive) { bear.Draw(spriteBatch); } } foreach (Projectile projectile in projectiles) { projectile.Draw(spriteBatch); } foreach (Explosion explosion in explosions) { explosion.Draw(spriteBatch); } // draw score and health spriteBatch.DrawString(font, healthString, GameConstants.HEALTH_LOCATION, Color.White); spriteBatch.DrawString(font, scoreString, GameConstants.SCORE_LOCATION, Color.White); // if burgerDead then print Game Over font if (burgerDead) { spriteBatch.DrawString(font, GameConstants.GAME_OVER, GameConstants.GAME_OVER_LOCATION, Color.White); } spriteBatch.End(); base.Draw(gameTime);
} #region Public methods /// <summary> /// Gets the projectile sprite for the given projectile type /// </summary> /// <param name="type">the projectile type</param> /// <returns>the projectile sprite for the type</returns> public static Texture2D GetProjectileSprite(ProjectileType type) { // replace with code to return correct projectile sprite based on projectile type if (type == ProjectileType.FrenchFries) { return frenchFriesSprite; } if (type == ProjectileType.TeddyBear) { return teddyBearProjectileSprite; } else return null; } /// <summary> /// Adds the given projectile to the game /// </summary> /// <param name="projectile">the projectile to add</param> public static void AddProjectile(Projectile projectile) { projectiles.Add(projectile); } #endregion #region Private methods /// <summary> /// Spawns a new teddy bear at a random location /// </summary> private void SpawnBear() { // generate random location int x = GetRandomLocation(SPAWN_BORDER_SIZE, GameConstants.WINDOW_WIDTH SPAWN_BORDER_SIZE); int y = GetRandomLocation(SPAWN_BORDER_SIZE, GameConstants.WINDOW_HEIGHT SPAWN_BORDER_SIZE); // generate random velocity float speed = (RandomNumberGenerator.NextFloat(GameConstants.BEAR_SPEED_RANGE) + GameConstants.MIN_BEAR_SPEED); double angle = 2 * Math.PI * RandomNumberGenerator.NextDouble(); velocity.X = (float)Math.Cos(angle) * speed; velocity.Y = -1 * (float)Math.Sin(angle) * speed; velocity = new Vector2(velocity.X, velocity.Y);
// create new bear TeddyBear teddybear = new TeddyBear(Content, "teddybear", x, y, velocity); // make sure we don't spawn into a collision List<Rectangle> collisionRectangles = GetCollisionRectangles(); while (!CollisionUtils.IsCollisionFree(teddybear.CollisionRectangle, collisionRectangles)) { int xBear = GetRandomLocation(0, GameConstants.WINDOW_WIDTH); int yBear = GetRandomLocation(0, GameConstants.WINDOW_HEIGHT); teddybear = new TeddyBear(Content, "teddybear", xBear, yBear, velocity); } // add new bear to list bears.Add(teddybear); } /// <summary> /// Gets a random location using the given min and range /// </summary> /// <param name="min">the minimum</param> /// <param name="range">the range</param> /// <returns>the random location</returns> private int GetRandomLocation(int min, int range) { return min + RandomNumberGenerator.Next(range); } /// <summary> /// Gets a list of collision rectangles for all the objects in the game world /// </summary> /// <returns>the list of collision rectangles</returns> private List<Rectangle> GetCollisionRectangles() { List<Rectangle> collisionRectangles = new List<Rectangle>(); collisionRectangles.Add(burger.CollisionRectangle); foreach (TeddyBear bear in bears) { collisionRectangles.Add(bear.CollisionRectangle); } foreach (Projectile projectile in projectiles) { collisionRectangles.Add(projectile.CollisionRectangle); } foreach (Explosion explosion in explosions) { collisionRectangles.Add(explosion.CollisionRectangle); } return collisionRectangles; } /// <summary> /// Checks to see if the burger has just been killed /// </summary> private void CheckBurgerKill() {
// if burgerDead is false and health is less than or equal to zero if (!burgerDead && burger.Health <= 0 ) { // set burgerDead to true and health to zero burgerDead = true; burger.Health = 0; //play BurgerDeath cue soundBank.PlayCue("BurgerDeath"); } } #endregion } }