George  Alabi

George Alabi

  • NA
  • 1
  • 4.5k

Help with blocks in Breakout XNA C#

May 5 2011 9:13 AM

I've stuck on creating multiple rows of block, any help will be appreciated

i've uploaded the source code


Thanks in advance 

code preview:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace XNA_Breakout
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        //Game world data

        //Application windows data
        float windowWidth;
        float windowHeight;
        float overScan = 10.0f;
        float windowMinX;
        float windowMaxX;
        float windowMinY;
        float windowMaxY;

        //Data for the application's ball 
        Texture2D ballTexture;
        Rectangle ballRect;
        float ballX;
        float ballXSpeed;
        float ballY;
        float ballYSpeed;
        float ballSize = 0.04f;

        //Data for the application's paddle
        Texture2D paddleTexture;
        Rectangle paddleRect;
        float paddleX;
        float paddleXSpeed;
        float paddleY;
        float paddleSize = 0.15f;

        //Data for the application's bricks
        Texture2D brickTexture;
        GameSpriteStruct[] bricks;  //Define bricks array
        int noOfBricks = 10;        //Number of bricks to be displayed

        //These variables represent audio files
        SoundEffect collisionWave;
        SoundEffect missWave;

        //Define variables of type Font to be used to display text
        SpriteFont font;

        //Various game variables
        int plays = 3;              //A game consists of 3 plays
        int noObVisibleBricks;      //Tracks the number of visisble bricks
        int playerScore = 0;        //Tracks player score
        bool stateOfGame = false;   //Tracks game state
        float space;               //Used to determine space between bricks

        //This structure defines data for the game's bricks
        struct GameSpriteStruct
        {
            public Texture2D spriteTexture;
            public Rectangle spriteRect;
            public float X;
            public float Y;
            public float WidthFactor;
            public bool Visible;
        }

        GameSpriteStruct splash;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);

            this.graphics.PreferredBackBufferWidth = 1280;
            this.graphics.PreferredBackBufferHeight = 720;
            this.graphics.IsFullScreen = false;

            Content.RootDirectory = "Content";
        }

        /// <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()
        {
            ConfigureScreen();  //This method establishes screen configuration

            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);

            //Load the game's graphic files into memory
            ballTexture = Content.Load<Texture2D>("ball");
            paddleTexture = Content.Load<Texture2D>("paddle");
            brickTexture = Content.Load<Texture2D>("redbrick");
            splash.spriteTexture = Content.Load<Texture2D>("splash");

            //Call method that configures the game's ball and paddle
            ConfigureBallAndPaddle();

            //Load the game's audio files into memory
            collisionWave = Content.Load<SoundEffect>("collision");
            missWave = Content.Load<SoundEffect>("miss");

            //Load the game's font
            font = Content.Load<SpriteFont>("SpriteFont1");

            //Instantiate a bricks object
            bricks = new GameSpriteStruct[noOfBricks];
            
            ConfigureBricks();  //Call on method that configures the bricks
            DisplaySplashScreen();  //Call on method that displays the splash screen
        }

        /// <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)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            //Retrieve gamepad state data
            GamePadState gamePad1 = GamePad.GetState(PlayerIndex.One);

            //Start game play when the player presses the gamepad's A button
            if (gamePad1.Buttons.A == ButtonState.Pressed)
            {
                StartGame();  //This method starts game play
            }

            if (stateOfGame == true)  //A value of true indicates active game play
            {
                //Determine the paddle's location
                paddleX = paddleX + (paddleXSpeed * gamePad1.ThumbSticks.Left.X);

                ProcessPaddleMovement();
                ProcessBallMovement();
                KeepTrackOfBricks();
            }

            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);
            Vector2 textVector1 = new Vector2(40, 30);

            spriteBatch.Begin();

            spriteBatch.Draw(ballTexture, ballRect, Color.White);
            spriteBatch.Draw(paddleTexture, paddleRect, Color.White);
            spriteBatch.DrawString(font, "Lives: " + plays.ToString() +
                "   Points: " + playerScore.ToString(), textVector1, Color.Black);


            switch (stateOfGame)
            {
                case false:  //A alue of false means its time to display the splash screen
                    spriteBatch.Draw(splash.spriteTexture, splash.spriteRect, Color.White);
                    break;
                 //A value of true indicates active game play
                    //Draw the ball, paddle and score
                   
                    //Draw only visible bricks

                    for (int i = 0; i < noOfBricks; i++)
                    {


                                if (bricks[i].Visible)
                                {
                                    spriteBatch.Draw(bricks[i].spriteTexture, bricks[i].spriteRect, Color.White);
                                    
                                }
                               

                        for (int k = 0; k < noOfBricks; k++)
                        {


                            if (bricks[k].Visible)
                            {
                               
                                spriteBatch.Draw(bricks[k].spriteTexture, bricks[k].spriteRect, Color.White);
                            }
                        }
                        break;
                    }
                    spriteBatch.End();

                    base.Draw(gameTime);

            }
        }
            
        
        //This method establishes screen configuration
        private void ConfigureScreen()
        {
            //Set window width and height
            windowWidth = graphics.GraphicsDevice.Viewport.Width;
            windowHeight = graphics.GraphicsDevice.Viewport.Height;

            //Calculate the over scan margin (for Xbox 360)
            float xOverscanMargin = (windowWidth * overScan) / 100;
            float yOverscanMargin = (windowHeight * overScan) / 100;

            //Use the over scan margin to set the game's boarders
            windowMinX = xOverscanMargin;
            windowMinY = yOverscanMargin;
            windowMaxX = windowWidth - xOverscanMargin;
            windowMaxY = windowHeight - yOverscanMargin;

            //Position the paddle at the bottom of the window
            paddleY = windowMaxY - 20;
        }

        void ConfigureBallAndPaddle()
        {
            //Set ball size
            ballRect.Width = (int)((windowWidth * ballSize) + 0.5f);
            float ratio = (float)ballTexture.Width / ballTexture.Height;
            ballRect.Height = (int)((ballRect.Width / ratio) + 0.5f);

            //Position the ball at the bottom center of the window just
            //above the paddle
            ballY = windowMaxY - 80;
            ballX = (windowWidth - ballRect.Width) / 2;

            ballXSpeed = windowWidth / 140.0f;    //Set ball's horizontal speed
            ballYSpeed = ballXSpeed * -1;         //Set ball's vertical speed

            //Set paddle size
            paddleRect.Width = (int)((windowWidth * paddleSize) + 0.5f);
            ratio = (float)paddleTexture.Width / paddleTexture.Height;
            paddleRect.Height = (int)((paddleRect.Width / ratio) + 0.5f);

            //Position the paddle at the bottom center of the window
            paddleX = (windowWidth - paddleRect.Width) / 2;

            paddleXSpeed = windowWidth / 100.0f;  //Set speed the paddle can move
        }

        //This method start game play
        private void StartGame()
        {
            stateOfGame = true; //A value of true initiates game play
            plays = 3;          //Reset the player's lives
            playerScore = 0;    //Reset the player's score

            ConfigureBricks();  //This method reconfigures a new screen of bricks
        }

        private void ProcessPaddleMovement()
        {
            paddleRect.X = (int)paddleX;  //Set the paddle's horizontal location
            paddleRect.Y = (int)paddleY;  //Set the paddle's vertical location

            //Halt paddle when it reaches the right edge of the display area
            if (paddleX + paddleRect.Width >= windowMaxX)
            {
                paddleRect.X = (int)windowMaxX - paddleRect.Width;
            }

            //Halt paddle when it reaches the left edge of the display area
            if (paddleX <= windowMinX) paddleRect.X = (int)windowMinX;
        }

        private void ProcessBallMovement()
        {
            //Determine the ball's location
            ballX = ballX + ballXSpeed;
            ballY = ballY + ballYSpeed;

            ballRect.X = (int)(ballX + 0.5f); //Set the ball's horizontal location
            ballRect.Y = (int)(ballY + 0.5f); //Set the ball's vertical location

            //Reverse ball direction along the X-axis when it reaches the right
            //hand side of the display area
            if (ballX + ballRect.Width >= windowMaxX)
            {
                ballXSpeed = ballXSpeed * -1;
                collisionWave.Play();           //Play sound effect
            }

            //Reverse ball direction along the X-axis when it reaches the
            //left hand side of the display area
            if (ballX <= windowMinX)
            {
                ballXSpeed = ballXSpeed * -1;
                collisionWave.Play();           //Play sound effect
            }

            //Halt the current round of play if the ball reaches the bottom
            //of the display area
            if (ballY + ballRect.Height >= windowMaxY)
            {
                missWave.Play();           //Play sound effect
                plays = plays - 1;         //Take away one of the player's lives
                ConfigureBallAndPaddle();

                //Mark the game as over when the player lives are gone
                if (plays == 0) stateOfGame = false;
            }

            //Reverse ball direction along the Y-axis when the ball reaches the 
            //top of the display area
            if (ballY <= windowMinY)
            {
                ballYSpeed = ballYSpeed * -1;
                collisionWave.Play();           //Play sound effect
            }

            //Reverse ball direction along the Y-axis when it collides 
            //with the paddle
            if (ballRect.Intersects(paddleRect))
            {
                ballYSpeed = ballYSpeed * -1;
                collisionWave.Play();           //Play sound effect
            }
        }

        private void KeepTrackOfBricks()
        {
            
            //Iterate once for evey brick
            for (int i = 0;  i < noOfBricks; i++)
            {
                //Check to see if the brick is visible 
                if (bricks[i].Visible)
                {
                    //Process a collision between the ball and a brick
                    if (ballRect.Intersects(bricks[i].spriteRect))
                    {
                        bricks[i].Visible = false;  //Mark the brick as invisible
                        noObVisibleBricks = noObVisibleBricks - 1; //Update brick count
                        playerScore = playerScore + 10;  //Increase the player's score
                        ballYSpeed = ballYSpeed * -1;  //Reverse the movement of the ball
                        collisionWave.Play();           //Play sound effect
                        break;  //Exit the loop
                    }
                }

                //Set the X and Y coordinates for the brick
                bricks[i].spriteRect.X = (int)bricks[i].X;
                bricks[i].spriteRect.Y = (int)bricks[i].Y;
                
            }

            //If there are not more bricks left then redisplay them again
            if (noObVisibleBricks == 0) ConfigureBricks();
        }

        //This methods configures the display of red bricks across the top
        //of the game window
        private void ConfigureBricks()
        {
            //Calculate the spacing betwen the bricks
            space = (windowMaxX - windowMinX) / noOfBricks;

            //Set variable equal to the total number of bricks
            noObVisibleBricks = noOfBricks;

            //This loop populates the bricks array with bricks, configure them and
            //marks them as visible
            for (int i = 0; i < noOfBricks; i++)
            {
                bricks[i].spriteTexture = brickTexture;
                bricks[i].WidthFactor = 0.08f;
                bricks[i].spriteRect.Width = (int)((windowWidth * 0.08f) + 0.5f);
                float ratio =
                    (float)bricks[i].spriteTexture.Width / bricks[i].spriteTexture.Height;
                bricks[i].spriteRect.Height =
                    (int)((bricks[i].spriteRect.Width / ratio) + 0.5f);
                bricks[i].X = windowMinX + (i * space);
                bricks[i].Y = windowMinY + 50;
                bricks[i].Visible = true;
            }
        }

        private void DisplaySplashScreen()
        {
            //Display the game's splash screen
            splash.spriteRect = new Rectangle((int)windowMinX, (int)windowMinY,
                (int)(windowMaxX - windowMinX), (int)(windowMaxY - windowMinY));
        }
        
    }
}


Answers (1)