Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
XNA 4.0 Game Development by Example: Beginner's Guide
XNA 4.0 Game Development by Example: Beginner's Guide

XNA 4.0 Game Development by Example: Beginner's Guide: The best way to start creating your own games is simply to dive in and give it a go with this Beginner’s Guide to XNA. Full of examples, tips, and tricks for a solid grounding.

eBook
$9.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

XNA 4.0 Game Development by Example: Beginner's Guide

Chapter 2. Flood Control – Underwater Puzzling

It was just another day at the bottom of the ocean until an explosion in one of the storage bays cracked the protective dome around Deep Sea Research Lab Alpha. Now the entire place is flooding, and the emergency pump system is a chaotic jumble of loose parts.

This chapter focuses on the following concepts:

  • Using the Content Pipeline to load textures from disk

  • Creating classes to divide code into logical units

  • Recursively evaluating the status of the game board to check for scoring chains

  • Drawing textures using the SpriteBatch.Draw() method

  • Managing simple game states

Designing a puzzle game


The Puzzler has always been a popular game genre. From old standbys like Tetris to modern crazes like Bejeweled, puzzle games are attractive to players because they do not require a long-term time investment or a steep learning curve.

The game mechanic is the heart of any good puzzle game. This mechanic is usually very simple, with perhaps a few twists to keep the players on their toes.

In Flood Control, the player will be faced with a board containing 80 pieces of pipe. Some will be straight pipes and some will be curved. The objective of the game is to rotate the pipes to form a continuous line to pump water from the left side of the board to the right side of the board.

Completing a section of pipe drains water out of the base and scores points for the player, but destroys the pipes used. New pipes will fall into place for the player to begin another row.

Time for action – set up the Flood Control project


  1. Open Visual Studio Express Edition (If it is already open, select Close Solution from the File menu so you are starting with an empty slate).

  2. In the Visual Studio window, open the File menu and select New Project...

  3. Under Project Type, make sure XNA Game Studio 4.0 is selected.

  4. Under Templates, select Windows Game (4.0).

  5. Name the project Flood Control.

  6. Click on OK.

  7. Right-click on Flood ControlContent (Content) in the Solution Explorer window and select Add | New Folder. Name the folder Textures.

  8. Add another folder under Flood ControlContent (Content) and name the folder Fonts.

  9. Download the 0669_02_GRAPHICPACK.zip file from the book's companion website and extract the files to a temporary folder.

  10. Back in Visual Studio, right-click on Textures in the Content project and click on Add | Existing Item. Browse to the folder where you extracted the 0669_02_GRAPHICPACK files and highlight all of them. Click on Add to add them to your project.

What just happened...

Introducing the Content Pipeline


The Flood ControlContent (Content) project inside Solution Explorer is a special kind of project called a Content Project. Items in your game's content project are converted into .XNB resource files by Content Importers and Content Processors.

If you right-click on one of the image files you just added to the Flood Control project and select Properties, you will see that for both the Importer and Processor, the Content Pipeline will use Texture – XNA Framework. This means that the Importer will take the file in its native format (.PNG in this case) and convert it to a format that the Processor recognizes as an image. The Processor then converts the image into an .XNB file which is a compressed binary format that XNA's content manager can read directly into a Texture2D object.

There are Content Importer/Processor pairs for several different types of content—images, audio, video, fonts, 3D models, and shader language effects files. All of these content types...

Time for action – reading textures into memory


  1. Double-click on Game1.cs in Solution Explorer to open it or bring it to the front if it is already open.

  2. In the Class Declarations area of Game1 (right below SpriteBatch spriteBatch;), add:

    Texture2D playingPieces;
    Texture2D backgroundScreen;
    Texture2D titleScreen;
  3. Add code to load each of the Texture2D objects at the end of LoadContent():

    playingPieces = Content.Load<Texture2D>(@"Textures\Tile_Sheet");
    backgroundScreen = Content.Load<Texture2D>(@"Textures\Background");
    titleScreen = Content.Load<Texture2D>(@"Textures\TitleScreen");
    

What just happened?

In order to load the textures from disk, you need an in-memory object to hold them. These are declared as instances of the Texture2D class.

A default XNA project sets up the Content instance of the ContentManager class for you automatically. The Content object's Load() method is used to read .XNB files from disk and into the Texture2D instances declared earlier.

One thing to note...

Sprites and sprite sheets


As far as XNA and the SpriteBatch class are concerned, a sprite is a 2D bitmapped image that can be drawn either with or without transparency information to the screen.

Tip

Sprites vs. Textures

XNA defines a "sprite" as a 2D bitmap that is drawn directly to the screen. While these bitmaps are stored in Texture2D objects, the term "texture" is used when a 2D image is mapped onto a 3D object, providing a visual representation of the surface of the object. In practice, all XNA graphics are actually performed in 3D, with 2D sprites being rendered via special configurations of the XNA rendering engine.

The simple form of the SpriteBatch.Draw() call that you used in Chapter 1 when drawing squares only needed three parameters: a Texture2D to draw, a Rectangle indicating where to draw it, and a Color to specify the tint to overlay onto the sprite.

Other overloads of the Draw() method, however, also allow you to specify a Rectangle representing the source area within the Texture2D...

Classes used in Flood Control


While it would certainly be possible to simply pile all of the game code into the Game1 class, the result would be difficult to read and manage later on. Instead, we need to consider how to logically divide the game into classes that can manage themselves and help to organize our code.

A good rule of thumb is that a class should represent a single thing or type of thing. If you can say "This object is made up of these other objects" or "This object contains these objects", consider creating classes to represent those relationships.

The Flood Control game contains a game board made up of 80 pipes. We can abstract these pipes as a class called GamePiece, and provide it with the code it needs to handle rotation and provide the code that will display the piece with a Rectangle that can be used to pull the sprite off the sprite sheet.

The game board itself can be represented by a GameBoard class, which will handle managing individual GamePiece objects and be responsible...

The GamePiece class


The GamePiece class represents an individual pipe on the game board. One GamePiece has no knowledge of any other game pieces (that is the responsibility of the GameBoard class), but it will need to be able to provide information about the pipe to objects that use the GamePiece class. Our class has the following requirements:

  • Identify the sides of each piece that contain pipe connectors

  • Differentiate between game pieces that are filled with water and that are empty

  • Allow game pieces to be updated

  • Automatically handle rotation by changing the piece type to the appropriate new piece type

  • Given one side of a piece, provide the other sides of the piece in order to facilitate determining where water can flow through the game board

  • Provide a Rectangle that will be used when the piece is drawn, to locate the graphic for the piece on the sprite sheet

Identifying a GamePiece

While the sprite sheet contains thirteen different images, only twelve of them are actual game pieces (the last...

Time for action – build a GamePiece class – declarations


  1. Switch back to your Visual C# window if you have your image editor open.

  2. Right-click on Flood Control in Solution Explorer and select Add | Class…

  3. Name the class GamePiece.cs and click on Add.

  4. At the top of the GamePiece.cs file, add the following to the using directives already in the class:

    using Microsoft.Xna.Framework.Graphics;
    using Microsoft.Xna.Framework;
  5. In the class declarations section, add the following:

      public static string[] PieceTypes = 
      { 
        "Left,Right", 
        "Top,Bottom", 
        "Left,Top", 
        "Top,Right",
        "Right,Bottom", 
        "Bottom,Left",
        "Empty"
      };
    
      public const int PieceHeight = 40;
      public const int PieceWidth = 40;
    
      public const int MaxPlayablePieceIndex = 5;
      public const int EmptyPieceIndex = 6;
    
      private const int textureOffsetX = 1;
      private const int textureOffsetY = 1;
      private const int texturePaddingX = 1;
      private const int texturePaddingY = 1;
    
      private string pieceType = "";
    ...

Time for action – building a GamePiece class: constructors


  1. Add two constructors to your GamePiece.cs file after the declarations:

      public GamePiece(string type, string suffix)
      {
          pieceType = type;
          pieceSuffix = suffix;
      }
    
      public GamePiece(string type)
      {
          pieceType = type;
          pieceSuffix = "";
      }

What just happened?

A constructor is run when an instance of the GamePiece class is created. By specifying two constructors, we will allow future code to create a GamePiece by specifying a piece type with or without a suffix. If no suffix is specified, an empty suffix is assumed.

Updating a GamePiece

When a GamePiece is updated, you can change the piece type, the suffix, or both.

Time for action – GamePiece class methods – part 1 – updating


  1. Add the following methods to the GamePiece class:

      public void SetPiece(string type, string suffix)
      {
          pieceType = type;
          pieceSuffix = suffix;
      }
      
      public void SetPiece(string type)
      {
          SetPiece(type,"");
      }
    
      public void AddSuffix(string suffix)
      {
          if (!pieceSuffix.Contains(suffix))
              pieceSuffix += suffix;
      }
    
      public void RemoveSuffix(string suffix)
      {
          pieceSuffix = pieceSuffix.Replace(suffix, "");
      }

The first two methods are overloads with the same name, but different parameter lists. In a manner similar to the GamePiece constructors, code that wishes to update a GamePiece can pass it a piece type, and optionally a suffix.

Additional methods have been added to modify suffixes without changing the pieceType associated with the piece. The AddSuffix() method first checks to see if the piece already contains the suffix. If it does, nothing happens. If it does not, the suffix value...

Time for action – GamePiece class methods – part 2 – rotation


  1. Add the RotatePiece() method to the GamePiece class:

      public void RotatePiece(bool Clockwise)
      {
          switch (pieceType)
          {
              case "Left,Right":
                  pieceType = "Top,Bottom";
                  break;
              case "Top,Bottom":
                  pieceType = "Left,Right";
                  break;
              case "Left,Top":
                  if (Clockwise)
                      pieceType = "Top,Right";
                  else
                      pieceType = "Bottom,Left";
                  break;
              case "Top,Right":
                  if (Clockwise)
                      pieceType = "Right,Bottom";
                  else
                      pieceType = "Left,Top";
                  break;
              case "Right,Bottom":
                  if (Clockwise)
                      pieceType = "Bottom,Left";
                  else
                      pieceType = "Top,Right";
                  break;
              case "Bottom,Left":
                  if (Clockwise)
                ...

Time for action – GamePiece class methods – part 3 – connection methods


  1. Add the GetOtherEnds() method to the GamePiece class:

      public string[] GetOtherEnds(string startingEnd)
      {
          List<string> opposites = new List<string>();
    
          foreach (string end in pieceType.Split(','))
          {
              if (end != startingEnd)
                  opposites.Add(end);
          }
           return opposites.ToArray();
      }
  2. Add the HasConnector() method to the GamePiece class:

      public bool HasConnector(string direction)
      {
          return pieceType.Contains(direction);
      }

The GetOtherEnds() method creates an empty List object for holding the ends we want to return to the calling code. It then uses the Split() method of the string class to get each end listed in the pieceType. For example, the Top,Bottom piece will return an array with two elements. The first element will contain Top and the second will contain Bottom. The comma delimiter will not be returned with either string.

If the end in question...

Time for action – GamePiece class methods – part 4 – GetSourceRect


  1. Add the GetSourceRect() method to the GamePiece class:

      public Rectangle GetSourceRect()
      {
          int x = textureOffsetX;
          int y = textureOffsetY;
            
          if (pieceSuffix.Contains("W"))
              x += PieceWidth + texturePaddingX;
    
          y += (Array.IndexOf(PieceTypes, pieceType) * 
               (PieceHeight + texturePaddingY));
    
    
          return new Rectangle(x, y, PieceWidth, PieceHeight);
      }

What just happened?

Initially, the x and y variables are set to the textureOffsets that are listed in the GamePiece class declaration. This means they will both start with a value of one.

Because the sprite sheet is organized with a single type of pipe on each row, the x coordinate of the Rectangle is the easiest to determine. If the pieceSuffix variable does not contain a W (signifying that the piece is filled with water), the x coordinate will simply remain 1.

If the pieceSuffix does contain the letter W (indicating the pipe...

The GameBoard class


Now that we have a way to represent pieces in memory, the next logical step is to create a way to represent an entire board of playing pieces.

The game board is a two-dimensional array of GamePiece objects, and we can build in some additional functionality to allow our code to interact with pieces on the game board by their X and Y coordinates.

The GameBoard class needs to:

  • Store a GamePiece object for each square on the game board

  • Provide methods for code using the GameBoard to update individual pieces by passing calls through to the underlying GamePiece instances

  • Randomly assign a piece type to a GamePiece

  • Set and clear the "Filled with water" flags on individual GamePieces

  • Determine which pipes should be filled with water based on their position and orientation and mark them as filled

  • Return lists of potentially scoring water chains to code using the GameBoard

Time for action – create the GameBoard.cs class


  1. As you did to create the GamePiece class, right-click on Flood Control in Solution Explorer and select Add | Class... Name the new class file GameBoard.cs.

  2. Add the using directive for the XNA framework at the top of the file:

    using Microsoft.Xna.Framework;
  3. Add the following declarations to the GameBoard class:

      Random rand = new Random();
    
      public const int GameBoardWidth = 8;
      public const int GameBoardHeight = 10;
    
      private GamePiece[,] boardSquares = 
        new GamePiece[GameBoardWidth, GameBoardHeight];
      private List<Vector2> WaterTracker = new List<Vector2>();

What just happened?

We used the Random class in SquareChase to generate random numbers. Since we will need to randomly generate pieces to add to the game board, we need an instance of Random in the GameBoard class.

The two constants and the boardSquares array provide the storage mechanism for the GamePiece objects that make up the 8 by 10 piece board.

Finally, a List of...

Time for action – initialize the game board


  1. Add a constructor to the GameBoard class:

      public GameBoard()
      {
          ClearBoard();
      }
  2. Add the ClearBoard() helper method to the GameBoard class:

      public void ClearBoard()
      {
          for (int x = 0; x < GameBoardWidth; x++)
              for (int y = 0; y < GameBoardHeight; y++)
                  boardSquares[x, y] = new GamePiece("Empty");
      }

What just happened?

When a new instance of the GameBoard class is created, the constructor calls the ClearBoard() helper method, which simply creates 80 empty game pieces and assigns them to each element in the array.

Tip

Helper methods

Why not simply put the two for loops that clear the board into the GameBoard constructor? Splitting the work into methods that accomplish a single purpose greatly helps to keep your code both readable and maintainable. Additionally, by splitting ClearBoard() out as its own method we can call it separately from the constructor. When we add increasing difficulty levels in Chapter...

Time for action – manipulating the game board


  1. Add public methods to the GameBoard class to interact with GamePiece:

      public void RotatePiece(int x, int y, bool clockwise)
      {
          boardSquares[x, y].RotatePiece(clockwise);
      }
    
      public Rectangle GetSourceRect(int x, int y)
      {
          return boardSquares[x, y].GetSourceRect();
      }
    
      public string GetSquare(int x, int y)
      {
          return boardSquares[x, y].PieceType;
      }
    
      public void SetSquare(int x, int y, string pieceName)
      {
          boardSquares[x, y].SetPiece(pieceName);
      }
    
      public bool HasConnector(int x, int y, string direction)
      {
          return boardSquares[x, y].HasConnector(direction); 
      }
    
      public void RandomPiece(int x, int y)
      {
        boardSquares[x, y].SetPiece(GamePiece.PieceTypes[rand.Next(0, 
             GamePiece.MaxPlayablePieceIndex+1)]);
      }
    

What just happened?

RotatePiece(), GetSourceRect(), GetSquare(), SetSquare(), and HasConnector() methods simply locate the appropriate GamePiece within the boardSquares array and...

Time for action – filling in the gaps


  1. Add the FillFromAbove() method to the GameBoard class.

    public void FillFromAbove(int x, int y)
    {
        int rowLookup = y - 1;
    
        while (rowLookup >= 0)
        {
            if (GetSquare(x, rowLookup) != "Empty")
            {
                SetSquare(x, y,
                  GetSquare(x, rowLookup));
                SetSquare(x, rowLookup, "Empty");
                rowLookup = -1;
            }
            rowLookup--;
        }
    }

What just happened?

Given a square to fill, FillFromAbove() looks at the piece directly above to see if it is marked as Empty. If it is, the method will subtract one from rowLookup and start over until it reaches the top of the board. If no non-empty pieces are found when the top of the board is reached, the method does nothing and exits.

When a non-empty piece is found, it is copied to the destination square, and the copied piece is changed to an empty piece. The rowLookup variable is set to -1 to ensure that the loop does not continue to run.

Generating new pieces...

Time for action – generating new pieces


  1. Add the GenerateNewPieces() method to the GameBoard class:

    public void GenerateNewPieces(bool dropSquares)
    {
    
        if (dropSquares)
        {
            for (int x = 0; x < GameBoard.GameBoardWidth; x++)
            {
                for (int y = GameBoard.GameBoardHeight - 1; y >= 0; y--)
                {
                    if (GetSquare(x, y) == "Empty")
                    {
                        FillFromAbove(x, y);
                    }
                }
            }
        }
    
        for (int y = 0; y < GameBoard.GameBoardHeight; y++)
            for (int x = 0; x < GameBoard.GameBoardWidth; x++)
            {
                if (GetSquare(x, y) == "Empty")
                {
                    RandomPiece(x, y);
                }
            }
    }

What just happened?

When GenerateNewPieces() is called with "true" passed as dropSquares, the looping logic processes one column at a time from the bottom up. When it finds an empty square it calls FillFromAbove() to pull a filled square from above into that location...

Time for action – water in the pipes


  1. Add a method to the GameBoard class to clear the water marker from all pieces:

      public void ResetWater()
      {
          for (int y = 0; y < GameBoardHeight; y++)
              for (int x = 0; x < GameBoardWidth; x++)
                  boardSquares[x,y].RemoveSuffix("W");
      }
  2. Add a method to the GameBoard class to fill an individual piece with water:

      public void FillPiece(int X, int Y)
      {
          boardSquares[X,Y].AddSuffix("W");
      }

What just happened?

The ResetWater() method simply loops through each item in the boardSquares array and removes the W suffix from the GamePiece. Similarly, to fill a piece with water, the FillPiece() method adds the W suffix to the GamePiece. Recall that by having a W suffix, the GetSourceRect() method of GamePiece shifts the source rectangle one tile to the right on the sprite sheet, returning the image for a pipe filled with water instead of an empty pipe.

Propagating water

Now that we can fill individual pipes with water, we can...

Time for action – making the connection


  1. Add the PropagateWater() method to the GameBoard class:

      public void PropagateWater(int x, int y, string fromDirection)
      {
          if ((y >= 0) && (y < GameBoardHeight) &&
              (x >= 0) && (x < GameBoardWidth))
          {
              if (boardSquares[x,y].HasConnector(fromDirection) &&
                  !boardSquares[x,y].Suffix.Contains("W"))
              {
                  FillPiece(x, y);
                  WaterTracker.Add(new Vector2(x, y));
                  foreach (string end in
                           boardSquares[x,y].GetOtherEnds(fromDirection))
                      switch (end)
                            {
                          case "Left": PropagateWater(x - 1, y, "Right");
                              break;
                          case "Right": PropagateWater(x + 1, y, "Left");
                              break;
                          case "Top": PropagateWater(x, y - 1, "Bottom");
                              break;
             ...

Building the game


We now have the component classes we need to build the Flood Control game, so it is time to bring the pieces together in the Game1 class.

Declarations

We only need a handful of game-wide declarations to manage things like the game board, the player's score, and the game state.

Time for action – Game1 declarations


  1. Double click on the Game1.cs file in Solution Explorer to reactivate the Game1.cs code file window.

  2. Add the following declarations to the Game1 class member declaration area:

    GameBoard gameBoard;
    
    Vector2 gameBoardDisplayOrigin = new Vector2(70, 89);
    
    int playerScore = 0;
    
    enum GameStates { TitleScreen, Playing };
    GameStates gameState = GameStates.TitleScreen;
    
    Rectangle EmptyPiece = new Rectangle(1, 247, 40, 40);
    
    const float MinTimeSinceLastInput = 0.25f;
    float timeSinceLastInput = 0.0f;

What just happened?

The gameBoard instance of GameBoard will hold all of the playing pieces, while the gameBoardDisplayOrigin vector points to where on the screen the board will be drawn. Using a vector like this makes it easy to move the board in the event that you wish to change the layout of your game screen.

As we did in SquareChase, we store the player's score and will display it in the window title bar.

In order to implement a simple game state mechanism, we define...

Time for action – updating the Initialize() method


  1. Update the Initialize() method to include the following:

    this.IsMouseVisible = true;
    graphics.PreferredBackBufferWidth = 800;
    graphics.PreferredBackBufferHeight = 600;
    graphics.ApplyChanges();
    gameBoard = new GameBoard();

What just happened?

After making the mouse cursor visible, we set the size of the BackBuffer to 800 by 600 pixels. On Windows, this will size the game window to 800 by 600 pixels as well.

The constructor for the GameBoard class calls the ClearBoard() member, so each of the pieces on the gameBoard instance will be set to Empty.

The Draw() method – the title screen

In the declarations section, we established two possible game states. The first (and default) state is GameStates.TitleScreen, indicating that the game should not be processing actual game play, but should instead be displaying the game's logo and waiting for the user to begin the game.

Time for action – drawing the screen – the title screen


  1. Modify the Draw() method of Game1 to include the code necessary to draw the game's title screen after GraphicsDevice.Clear(Color.CornflowerBlue);

    if (gameState == GameStates.TitleScreen)
    {
        spriteBatch.Begin();
        spriteBatch.Draw(titleScreen,
            new Rectangle(0, 0,
                this.Window.ClientBounds.Width,
                this.Window.ClientBounds.Height),
            Color.White);
        spriteBatch.End();
    }
  2. Run the game and verify that the title screen is displayed. You will not be able to start the game however, as we haven't written the Update() method yet.

  3. Stop the game by pressing Alt + F4.

What just happened?

The title screen is drawn with a single call to the Draw() method of the spriteBatch object. Since the title screen will cover the entire display, a rectangle is created that is equal to the width and height of the game window.

The Draw() method – the play screen

Finally, we are ready to display the playing pieces on the screen...

Time for action – drawing the screen – the play screen


  1. Update the Draw() method of the Game1 class to add the code to draw the game board after the code that draws the title screen:

    if (gameState == GameStates.Playing)
    {
        spriteBatch.Begin();
    
        spriteBatch.Draw(backgroundScreen,
            new Rectangle(0, 0,
                this.Window.ClientBounds.Width,
                this.Window.ClientBounds.Height),
            Color.White);
    
        for (int x = 0; x < GameBoard.GameBoardWidth; x++)
            for (int y = 0; y < GameBoard.GameBoardHeight; y++)
            {
                int pixelX = (int)gameBoardDisplayOrigin.X + 
                    (x * GamePiece.PieceWidth);
                int pixelY = (int)gameBoardDisplayOrigin.Y + 
                    (y * GamePiece.PieceHeight);
    
                spriteBatch.Draw(
                    playingPieces,
                    new Rectangle(
                      pixelX, 
                      pixelY, 
                      GamePiece.PieceWidth, 
                      GamePiece.PieceHeight),
             ...

Time for action – scores and scoring chains


  1. Add a method to the Game1 class to calculate a score based on the number of pipes used:

    private int DetermineScore(int SquareCount)
    {
        return (int)((Math.Pow((SquareCount/5), 2) + SquareCount)*10);
    }
  2. Add a method to evaluate a chain to determine if it scores and process it:

    private void CheckScoringChain(List<Vector2> WaterChain)
    {
    
        if (WaterChain.Count > 0)
        {
            Vector2 LastPipe = WaterChain[WaterChain.Count - 1];
    
    
            if (LastPipe.X == GameBoard.GameBoardWidth - 1)
            {
                if (gameBoard.HasConnector(
                    (int)LastPipe.X, (int)LastPipe.Y, "Right"))
                {
                    playerScore += DetermineScore(WaterChain.Count);
    
                    foreach (Vector2 ScoringSquare in WaterChain)
                    {
                        gameBoard.SetSquare((int)ScoringSquare.X,
                            (int)ScoringSquare.Y, "Empty");
                    }
                }
            }
        }
    }

What just happened?

DetermineScore...

Time for action – handling mouse input


  1. Add the HandleMouseInput() helper method to the Game1 class:

    private void HandleMouseInput(MouseState mouseState)
    {
    
        int x = ((mouseState.X -
            (int)gameBoardDisplayOrigin.X) / GamePiece.PieceWidth);
    
        int y = ((mouseState.Y -
            (int)gameBoardDisplayOrigin.Y) / GamePiece.PieceHeight);
    
        if ((x >= 0) && (x < GameBoard.GameBoardWidth) &&
          (y >= 0) && (y < GameBoard.GameBoardHeight))
        {
            if (mouseState.LeftButton == ButtonState.Pressed)
            {
                gameBoard.RotatePiece(x, y, false);
                timeSinceLastInput = 0.0f;
            }
    
            if (mouseState.RightButton == ButtonState.Pressed)
            {
                gameBoard.RotatePiece(x, y, true);
                timeSinceLastInput = 0.0f;
            }
        }
    }

What just happened?

The MouseState class reports the X and Y position of the mouse relative to the upper left corner of the window. What we really need to know is what square...

Time for action – letting the player play


  1. Modify the Update() method of Game1.cs by adding the following before the call to base.Update(gameTime):

    switch (gameState)
    {
        case GameStates.TitleScreen:
            if (Keyboard.GetState().IsKeyDown(Keys.Space))
            {
                gameBoard.ClearBoard();
                gameBoard.GenerateNewPieces(false);
                playerScore = 0;
                gameState = GameStates.Playing;
            }
            break;
    
        case GameStates.Playing:
            timeSinceLastInput +=
              (float)gameTime.ElapsedGameTime.TotalSeconds;
    
            if (timeSinceLastInput >= MinTimeSinceLastInput)
            {
                HandleMouseInput(Mouse.GetState());
            }
    
            gameBoard.ResetWater();
    
            for (int y = 0; y < GameBoard.GameBoardHeight; y++)
            {
                CheckScoringChain(gameBoard.GetWaterChain(y));        
            }
    
            gameBoard.GenerateNewPieces(true);
    
            break;
    }

What just happened?

The Update() method performs two different functions...

Play the game


You now have all of the components assembled, and can run Flood Control and play!

Summary


You now have a working Flood Control game. In this chapter we have looked at:

  • Adding content objects to your project and loading them into textures at runtime using an instance of the ContentManager class

  • Dividing the code into classes that represent objects in the game

  • Building a recursive method

  • Use the SpriteBatch.Draw() method to display images

  • Divide the Update() and Draw() code into different units based on the current game state

In Chapter 3, we will spruce up the Flood Control game, adding animation by modifying the parameters of the SpriteBatch.Draw() method and creating text effects in order to make the game visually more appealing.

Left arrow icon Right arrow icon

Key benefits

  • Dive headfirst into game creation with XNA
  • Four different styles of games comprising a puzzler, a space shooter, a multi-axis shoot 'em up, and a jump-and-run platformer
  • Games that gradually increase in complexity to cover a wide variety of game development techniques
  • Focuses entirely on developing games with the free version of XNA
  • Packed with many suggestions for expanding your finished game that will make you think critically, technically, and creatively
  • Fresh writing filled with many fun examples that introduce you to game programming concepts and implementation with XNA 4.0
  • A practical beginner's guide with a fast-paced but friendly and engaging approach towards game development

Description

XNA Game Studio enables hobbyists and independent game developers to easily create video games. It gives you the power to bring your creations to life on Windows, the Xbox 360, the Zune, and the Windows Phone platforms. But before you give life to your creativity with XNA, you need to gain a solid understanding of some game development concepts.This book covers both the concepts and the implementations necessary to get you started on bringing your own creations to life with XNA. It details the creation of four games, all in different styles, from start to finish using the Microsoft XNA Framework, including a puzzler, space shooter, multi-axis shoot-'em-up, and a jump-and-run platform game. Each game introduces new concepts and techniques to build a solid foundation for your own ideas and creativity. Beginning with the basics of drawing images to the screen, the book then incrementally introduces sprite animation, particles, sound effects, tile-based maps, and path finding. It then explores combining XNA with Windows Forms to build an interactive map editor, and builds a platform-style game using the editor-generated maps. Finally, the book covers the considerations necessary for deploying your games to the Xbox 360 platform.By the end of the book, you will have a solid foundation of game development concepts and techniques as well as working sample games to extend and innovate upon. You will have the knowledge necessary to create games that you can complete without an army of fellow game developers at your back.

Who is this book for?

If you are an aspiring game developer who wants to take a shot at creating games for the Microsoft Windows platform with the XNA Framework, then this book is for you. Using this book, you can get started with creating games without any game development experience. A basic knowledge of C# would be helpful to kick-start your game development, but it's not essential.

What you will learn

  • Install the Microsoft XNA Framework and its required tools
  • Build XNA Game projects and associated XNA Content projects
  • Create a puzzle-style game exploring the concepts of game states, recursion, and 2D animation
  • Add sound effects to your game with a "fire-and-forget" sound effects manager
  • Create a particle system to generate random explosions
  • Implement sound effects, collisions, and particle-based explosions by building a space shooter inside a chaotic asteroid field.
  • Implement the A path-finding algorithm to allow enemies to track down the player
  • Generate tile-based maps and path-finding enemy tanks amidst a storm of bullets in a multi-axis shooter
  • Combine XNA and Windows Forms to create a map editor for a multi-layered tile map engine
  • Run, jump, and squash enemies in a side-scrolling platform using the maps from your editor
  • Modify your creations for the Xbox 360 platform and deploy your games to the console
Estimated delivery fee Deliver to South Korea

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 24, 2010
Length: 428 pages
Edition : 1st
Language : English
ISBN-13 : 9781849690669
Vendor :
Microsoft
Concepts :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to South Korea

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Publication date : Sep 24, 2010
Length: 428 pages
Edition : 1st
Language : English
ISBN-13 : 9781849690669
Vendor :
Microsoft
Concepts :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 158.97
XNA 4 3D Game Development by Example: Beginner's Guide
$54.99
Microsoft XNA 4.0 Game Development Cookbook
$54.99
XNA 4.0 Game Development by Example: Beginner's Guide
$48.99
Total $ 158.97 Stars icon
Banner background image

Table of Contents

9 Chapters
Introducing XNA Game Studio Chevron down icon Chevron up icon
Flood Control – Underwater Puzzling Chevron down icon Chevron up icon
Flood Control – Smoothing Out the Rough Edges Chevron down icon Chevron up icon
Asteroid Belt Assault – Lost in Space Chevron down icon Chevron up icon
Asteroid Belt Assault – Lost in Space
Creating the project
Time for action – creating the Asteroid Belt Assault project
Another definition for "sprite"
Time for action – declarations for the Sprite class
Time for action – Sprite constructor
Time for action – basic Sprite properties
Time for action – animation and drawing properties
Time for action – supporting collision detection
Time for action – adding animation frames
Time for action – updating the Sprite
Time for action – drawing the Sprite
A sprite-based star field
Time for action – creating the StarField class
Time for action – updating and drawing the StarField
Time for action – viewing the StarField in action
Animated sprites – asteroids
Time for action – building the AsteroidManager class
Time for action – positioning the asteroids
Time for action – checking the asteroid's position
Time for action – updating and drawing asteroids
Time for action – bouncing asteroids – part 1
Time for action – bouncing asteroids – part 2
Player and enemy shots
Time for action – adding the ShotManager class
Time for action – firing shots
Time for action – updating and drawing shots
Adding the player
Time for action – creating the PlayerManager class
Time for action – handling user input
Time for action – updating and drawing the player's ship
Enemy ships
Time for action – creating the Enemy class
Time for action – waypoint management
Time for action – enemy update and draw
Time for action – creating the EnemyManager class
Time for action – setting up the EnemyManager class
Time for action – spawning enemies
Time for action – updating and drawing the EnemyManager
Summary
Asteroid Belt Assault – Special Effects Chevron down icon Chevron up icon
Robot Rampage – Multi-Axis Mayhem Chevron down icon Chevron up icon
Robot Rampage – Lots and Lots of Bullets Chevron down icon Chevron up icon
Gemstone Hunter – Put on Your Platform Shoes Chevron down icon Chevron up icon
Gemstone Hunter – Standing on Your Own Two Pixels Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(20 Ratings)
5 star 60%
4 star 25%
3 star 5%
2 star 5%
1 star 5%
Filter icon Filter
Top Reviews

Filter reviews by




Roderick C. Dixon Jan 15, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great tool for learning XNA. Highly recommend it
Amazon Verified review Amazon
Mark Jan 21, 2011
Full star icon Full star icon Full star icon Full star icon Full star icon 5
As president of the Rockford .NET User Group I get asked to review books, not all of which I actually get around to review for one reason or another. Usually the book is not engaging me and I don't wind up getting deep enough into the book to write a decent review.This book, however is different. It has fully engaged me and I am thoroughly enjoying it. After working through 8 of the 9 chapters I feel I can offer a solid review.Overall the code has been excellent with only a couple minor typos that I've noted and the games have worked as they are supposed to. I'm learning a lot about XNA and vector math. (I've even written my first game!) I love the way the author explains the mathematics of what the code is doing - instead of just saying "this is what the code does", the author takes the time to explain (sometimes with illustrations) exactly how the code does what it does and why it works the way it does.I really like the way the author introduces a topic, then dives into the code, then follows the code with a "What Just Happened?" section that explains what the code just entered is supposed to do. The explanations are clear and easy to understand, but not "dumbed down."This book is proving itself very valuable in my development efforts.Thank you for a great book!
Amazon Verified review Amazon
Pule Nong Jun 27, 2011
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I bought an ebook version of this book from the publisher's site. This is a practical hands on approach type of book, just at the end of the first chapter I had already built a game called SquareChase.I am not proficient in C# but I was able to follow along very well. The code is easy to read, understand and follow.You do not need to know C# to read this textbook.The book comprises of 4 games that you build as you go along and all these games are interesting. I have already mentioned SquareChase, the other 3 games are flood control, asteroid belt assault and robot rampage. These games are all engaging and fun to play too.This is a great book. I learned a lot from it despite the fact that I am not familiar with the C# programming language. Although I must mention that I have some programming experience working with PHP. I give this book a 100% rating - 5/5.
Amazon Verified review Amazon
Lance W. Larsen Dec 16, 2010
Full star icon Full star icon Full star icon Full star icon Full star icon 5
[…]Firstly, I'm the president of the Madison .NET User Group […] so I get lots of books to review - I generally don't end up doing so - as I get a chapter or two into them - then start skipping around and don't feel that I've read it thoroughly enough to give it a bad, let alone a good review.So when I DO give something a good review -- it really deserves it.And "XNA 4.0 Game Development by Example: Beginner's Guide" by Kurt Jaegers deserves a GREAT review. I'm not done with it yet, but I'm thoroughly engaged by their writing style - I love the way they they dive head first into code, and then follow it up with a "What Just Happened?" section that does a great job explaining in very simple (but not dumbed down) terms. Go here -- […] -- and look at the "Sample Chapter".On top of their writing style, the content is awesome - totally filling in a lot of the blanks and inspiring me to write new code ( which I'll be using for Windows Phone 7 XNA development ) - so look out for better games and (...wait for it... #shock# %gasp%) potential revenue from games that I publish because this book accelerated my learning new XNA techniques.So, in closing - GREAT book - very WELL written - ENGAGING content - HIGHLY encourage those even at all interested in writing Games to grab this book! And if you enjoy it half as much as I am, you will certainly keep this one close at hand while you're writing XNA code.Check out Kurt Jaegers' site - […]-- nice code here as well...!
Amazon Verified review Amazon
Melibojangles May 27, 2011
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you have been teaching yourself C#/XNA and are familiar with the concepts needed to create games but are struggling with how to put all those pieces together, this book is for you. For me, this book is just one a-ha moment after another. The code is clean and well documented and focuses on functionality rather than theory. This book is exactly what I needed to move to the next level, and expect to see my game on the Xbox Indie Marketplace soon.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela