Advertisement
SuperLemrick

BumperCars

Jun 12th, 2015
474
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 20.08 KB | None | 0 0
  1. ////////////////////////////////////////////////////////////////
  2. // Copyright 2013, CompuScholar, Inc.
  3. //
  4. // This source code is for use by the students and teachers who
  5. // have purchased the corresponding TeenCoder or KidCoder product.
  6. // It may not be transmitted to other parties for any reason
  7. // without the written consent of CompuScholar, Inc.
  8. // This source is provided as-is for educational purposes only.
  9. // CompuScholar, Inc. makes no warranty and assumes
  10. // no liability regarding the functionality of this program.
  11. //
  12. ////////////////////////////////////////////////////////////////
  13.  
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Linq;
  17. using Microsoft.Xna.Framework;
  18. using Microsoft.Xna.Framework.Audio;
  19. using Microsoft.Xna.Framework.Content;
  20. using Microsoft.Xna.Framework.GamerServices;
  21. using Microsoft.Xna.Framework.Graphics;
  22. using Microsoft.Xna.Framework.Input;
  23. using Microsoft.Xna.Framework.Media;
  24. using Microsoft.Xna.Framework.Net;
  25. using Microsoft.Xna.Framework.Storage;
  26.  
  27. using SpriteLibrary;
  28.  
  29.  
  30. namespace BumperCars
  31. {
  32.     public class BumperCars : Microsoft.Xna.Framework.Game
  33.     {
  34.         GraphicsDeviceManager graphics;
  35.         SpriteBatch spriteBatch;
  36.  
  37.         Texture2D car1Texture;
  38.         Texture2D car2Texture;
  39.         Texture2D oilSlickTexture;
  40.         Texture2D spinningCoinTexture;
  41.  
  42.         KeyboardState oldKeyState;
  43.  
  44.         GamePadState oldGamePadState1;
  45.         GamePadState oldGamePadState2;
  46.  
  47.         bool aiPlayerActive = false;
  48.  
  49.         const int NUM_OIL_SLICKS = 3;
  50.         const int SCORE_TO_WIN = 10;
  51.         const double ACCELERATION_FACTOR = 0.02;
  52.         const double MAX_SPEED = 3.0;
  53.  
  54.         const double STEER_FACTOR = 5;
  55.  
  56.         Car car1;
  57.         Car car2;
  58.  
  59.         SoundEffect bounceSound;
  60.         SoundEffect coinSound;
  61.         SoundEffect oilSlickSound;
  62.         SoundEffect backgroundMusic;
  63.  
  64.         SoundEffectInstance backMusicInstance;
  65.         SoundEffectInstance oilSlickInstance;
  66.  
  67.         SpriteFont gameFont;
  68.  
  69.         Sprite coin;
  70.  
  71.         LinkedList<Sprite> oilSlicks = new LinkedList<Sprite>();
  72.  
  73.         Random random = new System.Random();
  74.  
  75.         double lastOilSlick = 0;
  76.  
  77.         enum GameScreen
  78.         {
  79.             MENU = 0,
  80.             PLAYING = 1,
  81.             GAMEOVER = 2
  82.         }
  83.         GameScreen currentScreen;
  84.  
  85.         string displayMessage;
  86.  
  87.         public BumperCars()
  88.         {
  89.             graphics = new GraphicsDeviceManager(this);
  90.             Content.RootDirectory = "Content";
  91.         }
  92.  
  93.         protected override void Initialize()
  94.         {
  95.             currentScreen = GameScreen.MENU;
  96.  
  97.             base.Initialize();
  98.         }
  99.  
  100.         protected override void LoadContent()
  101.         {
  102.             spriteBatch = new SpriteBatch(GraphicsDevice);
  103.  
  104.             gameFont = this.Content.Load<SpriteFont>("GameFont");
  105.  
  106.             car1Texture = this.Content.Load<Texture2D>("Images\\bumper_car1");
  107.             car2Texture = this.Content.Load<Texture2D>("Images\\bumper_car2");
  108.             oilSlickTexture = this.Content.Load<Texture2D>("Images\\oil_slick");
  109.             spinningCoinTexture =
  110.                           this.Content.Load<Texture2D>("Images\\spinning_coin");
  111.  
  112.             bounceSound =
  113.                     this.Content.Load<SoundEffect>("Sound\\bumpercar_bounce");
  114.             coinSound = this.Content.Load<SoundEffect>("Sound\\bumpercar_coin");
  115.             oilSlickSound =
  116.                     this.Content.Load<SoundEffect>("Sound\\bumpercar_oilSlick");
  117.             backgroundMusic =
  118.                     this.Content.Load<SoundEffect>("Sound\\background_music");
  119.  
  120.             backMusicInstance = backgroundMusic.CreateInstance();
  121.             backMusicInstance.IsLooped = true;
  122.             backMusicInstance.Volume = .5f;
  123.  
  124.             oilSlickInstance = oilSlickSound.CreateInstance();
  125.  
  126.         }
  127.  
  128.         protected override void UnloadContent()
  129.         {
  130.  
  131.         }
  132.  
  133.         private void startGame()
  134.         {
  135.             currentScreen = GameScreen.PLAYING;
  136.  
  137.             car1 = new Car();
  138.             car1.SetTexture(car1Texture);
  139.             car1.Scale = new Vector2(1.5f, 1.5f);
  140.             car1.UpperLeft = new Vector2(10,
  141.                                        this.GraphicsDevice.Viewport.Height / 2);
  142.             car1.SetVelocity(1.0, 0.0);
  143.             car1.RotationAngle = 0;
  144.             car1.Origin = car1.GetCenter();
  145.             car1.MaxSpeed = MAX_SPEED;
  146.             car1.Score = 0;
  147.  
  148.             car2 = new Car();
  149.             car2.SetTexture(car2Texture);
  150.             car2.Scale = new Vector2(1.5f, 1.5f);
  151.             car2.UpperLeft = new Vector2(
  152.                      this.GraphicsDevice.Viewport.Width - 10 - car2.GetWidth(),
  153.                      this.GraphicsDevice.Viewport.Height / 2);
  154.             car2.SetVelocity(1.0, 0.0);
  155.             car2.RotationAngle = 180;
  156.             car2.RotationAngle = 0;
  157.             car2.Origin = car2.GetCenter();
  158.             car2.MaxSpeed = MAX_SPEED;
  159.             car2.Score = 0;
  160.  
  161.             coin = new Sprite();
  162.             coin.SetTexture(spinningCoinTexture, 5);
  163.             coin.AnimationInterval = 200;
  164.  
  165.             coin.Scale = new Vector2(1.5f, 1.5f);
  166.  
  167.             placeCoin();
  168.  
  169.             oilSlicks.Clear();
  170.  
  171.             for (int i = 0; i < NUM_OIL_SLICKS; i++)
  172.             {
  173.                 newOilSlick();
  174.             }
  175.  
  176.             backMusicInstance.Play();
  177.         }
  178.  
  179.         private void stopGame(String message)
  180.         {
  181.             currentScreen = GameScreen.GAMEOVER;
  182.             displayMessage = message;
  183.  
  184.             backMusicInstance.Stop();
  185.         }
  186.  
  187.         protected override void Update(GameTime gameTime)
  188.         {
  189.  
  190.             KeyboardState keyState = Keyboard.GetState();
  191.             if (oldKeyState == null)
  192.                 oldKeyState = keyState;
  193.  
  194.             GamePadState currentGamePad1 = GamePad.GetState(PlayerIndex.One);
  195.             GamePadState currentGamePad2 = GamePad.GetState(PlayerIndex.Two);
  196.  
  197.             if (oldGamePadState1 == null)
  198.                 oldGamePadState1 = currentGamePad1;
  199.  
  200.             if (oldGamePadState2 == null)
  201.                 oldGamePadState2 = currentGamePad2;
  202.  
  203.             switch (currentScreen)
  204.             {
  205.                 case GameScreen.MENU:
  206.                     updateMenu(gameTime, keyState);
  207.  
  208.                     break;
  209.                 case GameScreen.PLAYING:
  210.                     updatePlaying(gameTime, keyState);
  211.  
  212.                     break;
  213.                 case GameScreen.GAMEOVER:
  214.                     updateGameover(gameTime, keyState);
  215.                     break;
  216.  
  217.             }
  218.             oldKeyState = keyState;
  219.  
  220.             oldGamePadState1 = currentGamePad1;
  221.             oldGamePadState2 = currentGamePad2;
  222.  
  223.             base.Update(gameTime);
  224.         }
  225.  
  226.         private void updateMenu(GameTime gameTime, KeyboardState keyState)
  227.         {
  228.             if (keyState.IsKeyDown(Keys.Escape) &&
  229.                 oldKeyState.IsKeyUp(Keys.Escape))
  230.             {
  231.                 Exit();
  232.             }
  233.  
  234.             if (keyState.IsKeyDown(Keys.D1) && oldKeyState.IsKeyUp(Keys.D1))
  235.             {
  236.                 aiPlayerActive = true;
  237.                 startGame();
  238.             }
  239.             else if (keyState.IsKeyDown(Keys.D2) &&
  240.                      oldKeyState.IsKeyUp(Keys.D2))
  241.             {
  242.                 aiPlayerActive = false;
  243.                 startGame();
  244.             }
  245.         }
  246.  
  247.         private void updateMenuXbox(GamePadState player1GamePad,
  248.                                     GamePadState player2Gamepad)
  249.         {
  250.             if ((player1GamePad.Buttons.Back == ButtonState.Pressed &&
  251.                  oldGamePadState1.Buttons.Back == ButtonState.Released) ||
  252.                 (player2Gamepad.Buttons.Back == ButtonState.Pressed &&
  253.                  oldGamePadState2.Buttons.Back == ButtonState.Released))
  254.             {
  255.                 Exit();
  256.             }
  257.  
  258.             if ((player1GamePad.Buttons.A == ButtonState.Pressed &&
  259.                  oldGamePadState1.Buttons.A == ButtonState.Released) ||
  260.                 (player2Gamepad.Buttons.A == ButtonState.Pressed &&
  261.                  oldGamePadState2.Buttons.A == ButtonState.Released))
  262.             {
  263.                 aiPlayerActive = true;
  264.                 startGame();
  265.             }
  266.  
  267.             // if 'B' pressed
  268.             if ((player1GamePad.Buttons.B == ButtonState.Pressed &&
  269.                  oldGamePadState1.Buttons.B == ButtonState.Released) ||
  270.                 (player2Gamepad.Buttons.B == ButtonState.Pressed &&
  271.                  oldGamePadState2.Buttons.B == ButtonState.Released))
  272.             {
  273.                 aiPlayerActive = false;
  274.                 startGame();
  275.             }
  276.         }
  277.  
  278.         private void updatePlaying(GameTime gameTime, KeyboardState keyState)
  279.         {
  280.             if (keyState.IsKeyDown(Keys.A))
  281.             {
  282.                 car1.Steer(STEER_FACTOR);
  283.             }
  284.             if (keyState.IsKeyDown(Keys.D))
  285.             {
  286.                 car1.Steer(-STEER_FACTOR);
  287.             }
  288.             if (keyState.IsKeyDown(Keys.W))
  289.             {
  290.                 car1.Accelerate(ACCELERATION_FACTOR);
  291.             }
  292.             if (keyState.IsKeyDown(Keys.X))
  293.             {
  294.                 car1.Accelerate(-ACCELERATION_FACTOR);
  295.  
  296.                 if (!aiPlayerActive)
  297.                 {
  298.                     if (keyState.IsKeyDown(Keys.Left))
  299.                     {
  300.                         car2.Steer(STEER_FACTOR);
  301.                     }
  302.                     if (keyState.IsKeyDown(Keys.Right))
  303.                     {
  304.                         car2.Steer(-STEER_FACTOR);
  305.                     }
  306.                     if (keyState.IsKeyDown(Keys.Up))
  307.                     {
  308.                         car2.Accelerate(ACCELERATION_FACTOR);
  309.                     }
  310.                     if (keyState.IsKeyDown(Keys.Down))
  311.                     {
  312.                         car2.Accelerate(-ACCELERATION_FACTOR);
  313.                     }
  314.                 }
  315.                 else
  316.                 {
  317.                     DoAI();
  318.                 }
  319.  
  320.                 moveCars();
  321.  
  322.                 checkTimedEvents(gameTime);
  323.  
  324.                 coin.Animate(gameTime);
  325.  
  326.             }
  327.         }
  328.  
  329.         private void updatePlayingXbox(GameTime gameTime,
  330.                                        GamePadState currentGamePad1,
  331.                                        GamePadState currentGamePad2)
  332.         {
  333.             if (currentGamePad1.ThumbSticks.Left.X < 0)
  334.             {
  335.                 car1.Steer(STEER_FACTOR);
  336.             }
  337.             if (currentGamePad1.ThumbSticks.Left.X > 0)
  338.             {
  339.                 car1.Steer(-STEER_FACTOR);
  340.             }
  341.             if (currentGamePad1.ThumbSticks.Left.Y > 0)
  342.             {
  343.                 car1.Accelerate(ACCELERATION_FACTOR);
  344.             }
  345.             if (currentGamePad1.ThumbSticks.Left.Y < 0)
  346.             {
  347.                 car1.Accelerate(-ACCELERATION_FACTOR);
  348.             }
  349.  
  350.             if (!aiPlayerActive)
  351.             {
  352.                 if (currentGamePad2.ThumbSticks.Left.X < 0)
  353.                 {
  354.                     car2.Steer(STEER_FACTOR);
  355.                 }
  356.                 if (currentGamePad2.ThumbSticks.Left.X > 0)
  357.                 {
  358.                     car2.Steer(-STEER_FACTOR);
  359.                 }
  360.                 if (currentGamePad2.ThumbSticks.Left.Y > 0)
  361.                 {
  362.                     car2.Accelerate(ACCELERATION_FACTOR);
  363.                 }
  364.                 if (currentGamePad2.ThumbSticks.Left.Y < 0)
  365.                 {
  366.                     car2.Accelerate(-ACCELERATION_FACTOR);
  367.                 }
  368.             }
  369.             else
  370.             {
  371.                 DoAI();
  372.             }
  373.             moveCars();
  374.  
  375.             checkTimedEvents(gameTime);
  376.  
  377.             coin.Animate(gameTime);
  378.  
  379.         }
  380.         private int findQuadrant(double angle)
  381.         {
  382.             if ((angle >= 0) && (angle < 90))
  383.                 return 1;
  384.             if ((angle >= 90) && (angle < 180))
  385.                 return 2;
  386.             if ((angle >= 180) && (angle < 270))
  387.                 return 3;
  388.  
  389.             return 4;
  390.         }
  391.  
  392.         private int findLeftQuadrant(int quadrant)
  393.         {
  394.             if (quadrant < 3)
  395.                 return quadrant + 1;
  396.             else
  397.                 return 0;
  398.         }
  399.  
  400.         private int findRightQuadrant(int quadrant)
  401.         {
  402.             if (quadrant > 1)
  403.                 return quadrant - 1;
  404.             else
  405.                 return 4;
  406.         }
  407.         private void DoAI()
  408.         {
  409.  
  410.             double dx = coin.UpperLeft.X - car2.UpperLeft.X;
  411.             double dy = coin.UpperLeft.Y - car2.UpperLeft.Y;
  412.  
  413.             double angleToCoin = Sprite.CalculateDirectionAngle(
  414.                                              new Vector2((float)dx, (float)dy));
  415.  
  416.             double carDirectionAngle = car2.GetDirectionAngle();
  417.  
  418.             int coinAngleQuadrant = findQuadrant(angleToCoin);
  419.             int carAngleQuadrant = findQuadrant(carDirectionAngle);
  420.  
  421.             if (coinAngleQuadrant == carAngleQuadrant)
  422.             {
  423.                 double angleDifference = carDirectionAngle - angleToCoin;
  424.  
  425.                 if (Math.Abs(angleDifference) > STEER_FACTOR)
  426.                 {
  427.                     if (angleDifference < 0)
  428.                         car2.Steer(STEER_FACTOR);
  429.                     else
  430.                         car2.Steer(-STEER_FACTOR);
  431.                 }
  432.             }
  433.  
  434.             else if (findLeftQuadrant(carAngleQuadrant) == coinAngleQuadrant)
  435.             {
  436.                 car2.Steer(STEER_FACTOR);
  437.             }
  438.  
  439.             else if (findRightQuadrant(carAngleQuadrant) == coinAngleQuadrant)
  440.             {
  441.                 car2.Steer(-STEER_FACTOR);
  442.             }
  443.  
  444.             else
  445.             {
  446.                 car2.Steer(STEER_FACTOR);
  447.             }
  448.  
  449.             car2.Accelerate(ACCELERATION_FACTOR);
  450.         }
  451.  
  452.         private void updateGameover(GameTime gameTime, KeyboardState keyState)
  453.         {
  454.             if (keyState.IsKeyDown(Keys.Space) &&
  455.                 oldKeyState.IsKeyUp(Keys.Space))
  456.             {
  457.                 currentScreen = GameScreen.MENU;
  458.             }
  459.         }
  460.  
  461.         private void updateGameoverXbox(GamePadState player1GamePad,
  462.                                         GamePadState player2Gamepad)
  463.         {
  464.             if ((player1GamePad.Buttons.Back == ButtonState.Pressed &&
  465.                  oldGamePadState1.Buttons.Back == ButtonState.Released) ||
  466.                 (player2Gamepad.Buttons.Back == ButtonState.Pressed &&
  467.                  oldGamePadState2.Buttons.Back == ButtonState.Released))
  468.             {
  469.                 currentScreen = GameScreen.MENU;
  470.             }
  471.         }
  472.  
  473.         private void checkTimedEvents(GameTime gameTime)
  474.         {
  475.             if ((gameTime.TotalGameTime.TotalMilliseconds - lastOilSlick) > 5000)
  476.             {
  477.                 newOilSlick();
  478.                 lastOilSlick = gameTime.TotalGameTime.TotalMilliseconds;
  479.             }
  480.  
  481.         }
  482.  
  483.         private void placeCoin()
  484.         {
  485.             coin.UpperLeft.X = random.Next(0,
  486.                         this.GraphicsDevice.Viewport.Width - coin.GetWidth());
  487.             coin.UpperLeft.Y = random.Next(0,
  488.                         this.GraphicsDevice.Viewport.Height - coin.GetHeight());
  489.         }
  490.  
  491.         private void moveCars()
  492.         {
  493.             if (car1.MoveAndReflect(this.GraphicsDevice.Viewport.Width,
  494.                                     this.GraphicsDevice.Viewport.Height))
  495.                 bounceSound.Play();
  496.  
  497.             if (car2.MoveAndReflect(this.GraphicsDevice.Viewport.Width,
  498.                                     this.GraphicsDevice.Viewport.Height))
  499.                 bounceSound.Play();
  500.  
  501.             if (car1.CheckBump(car2, this.GraphicsDevice.Viewport.Width,
  502.                                      this.GraphicsDevice.Viewport.Height))
  503.                 bounceSound.Play();
  504.  
  505.             if (car1.IsCollided(coin))
  506.             {
  507.  
  508.                 car1.Score++;
  509.                 placeCoin();
  510.                 coinSound.Play();
  511.             }
  512.  
  513.             if (car2.IsCollided(coin))
  514.             {
  515.                 car2.Score++;
  516.                 placeCoin();
  517.                 coinSound.Play();
  518.             }
  519.  
  520.             foreach (Sprite slick in oilSlicks)
  521.             {
  522.                 if (car1.IsCollided(slick))
  523.                 {
  524.                     car1.SetSpeedAndDirection(0.5, car1.GetDirectionAngle());
  525.                     oilSlickInstance.Play();
  526.                 }
  527.                 if (car2.IsCollided(slick))
  528.                 {
  529.                     car2.SetSpeedAndDirection(0.5, car2.GetDirectionAngle());
  530.                     oilSlickInstance.Play();
  531.                 }
  532.             }
  533.  
  534.             if (car1.Score >= SCORE_TO_WIN)
  535.             {
  536.                 stopGame("Player 1 wins!");
  537.             }
  538.             else if (car2.Score >= SCORE_TO_WIN)
  539.             {
  540.                 stopGame("Player 2 wins!");
  541.             }
  542.         }
  543.  
  544.         private void newOilSlick()
  545.         {
  546.             Sprite slick = new Sprite();
  547.             slick.SetTexture(oilSlickTexture);
  548.             slick.Scale = new Vector2(2.0f, 2.0f);
  549.             slick.UpperLeft.X = random.Next(0,
  550.                      this.GraphicsDevice.Viewport.Width - slick.GetWidth());
  551.             slick.UpperLeft.Y = random.Next(0,
  552.                      this.GraphicsDevice.Viewport.Height - slick.GetHeight());
  553.  
  554.             oilSlicks.AddLast(slick);
  555.  
  556.             if (oilSlicks.Count > NUM_OIL_SLICKS)
  557.             {
  558.                 oilSlicks.RemoveFirst();
  559.             }
  560.         }
  561.  
  562.         /// <summary>
  563.         /// This is called when the game should draw itself.
  564.         /// </summary>
  565.         /// <param name="gameTime">Provides a snapshot of timing values.</param>
  566.         protected override void Draw(GameTime gameTime)
  567.         {
  568.             GraphicsDevice.Clear(Color.CornflowerBlue);
  569.  
  570.             spriteBatch.Begin();
  571.  
  572.             switch (currentScreen)
  573.             {
  574.                 case GameScreen.MENU:
  575.                     drawMenu(gameTime);
  576.                     break;
  577.                 case GameScreen.PLAYING:
  578.                     drawPlaying(gameTime);
  579.                     break;
  580.                 case GameScreen.GAMEOVER:
  581.                     drawGameOver(gameTime);
  582.                     break;
  583.             }
  584.  
  585.             spriteBatch.End();
  586.  
  587.             base.Draw(gameTime);
  588.         }
  589.  
  590.         private void drawMenu(GameTime gameTime)
  591.         {
  592.             spriteBatch.DrawString(gameFont,
  593.                                    "Press 1 for single-player game",
  594.                                    new Vector2(10, 10), Color.Black);
  595.             spriteBatch.DrawString(gameFont,
  596.                                    "Press 2 for two-player local game",
  597.                                    new Vector2(10, 30), Color.Black);
  598.             spriteBatch.DrawString(gameFont,
  599.                                    "Press ESC (or Back) to exit",
  600.                                    new Vector2(10, 50), Color.Black);
  601.         }
  602.  
  603.         private void drawPlaying(GameTime gameTime)
  604.         {
  605.             foreach (Sprite s in oilSlicks)
  606.             {
  607.                 s.Draw(spriteBatch);
  608.             }
  609.  
  610.             coin.Draw(spriteBatch);
  611.  
  612.             spriteBatch.DrawString(gameFont, "Player 1 Score: " + car1.Score,
  613.                                    new Vector2(10, 10), Color.Red);
  614.             spriteBatch.DrawString(gameFont, "Player 2 Score: " + car2.Score,
  615.                                    new Vector2(10, 30), Color.Yellow);
  616.  
  617.             car1.Draw(spriteBatch);
  618.             car2.Draw(spriteBatch);
  619.         }
  620.  
  621.         private void drawGameOver(GameTime gameTime)
  622.         {
  623.             spriteBatch.DrawString(gameFont, displayMessage,
  624.                     new Vector2(this.GraphicsDevice.Viewport.Width / 2 - 100,
  625.                     this.GraphicsDevice.Viewport.Height / 2 - 10), Color.Black);
  626.             spriteBatch.DrawString(gameFont,
  627.                     "Press <Space> to return to menu",
  628.                     new Vector2(this.GraphicsDevice.Viewport.Width / 2 - 100,
  629.                     this.GraphicsDevice.Viewport.Height / 2 + 10), Color.Black);
  630.         }
  631.     }
  632. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement