Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
XNA 4.0 Game Development by Example: Beginner's Guide - Visual Basic Edition
XNA 4.0 Game Development by Example: Beginner's Guide - Visual Basic Edition

XNA 4.0 Game Development by Example: Beginner's Guide - Visual Basic Edition: Create your own exciting games with Visual Basic and Microsoft XNA 4.0

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 - Visual Basic Edition

Chapter 1. Introducing XNA Game Studio

Since its initial release in 2006, the Microsoft XNA Framework has allowed C# developers to harness the power of DirectX to create video games that can be targeted to Windows, the Xbox 360, and Microsoft-based mobile devices such as the Zune or the Windows Phone 7 platform.

XNA consists of the XNA Framework, which is a set of code libraries to perform common graphics, sound, and other game-related tasks, and XNA Game Studio, which is an extension of the Visual Studio interface that includes a number of project templates to make use of the XNA Framework.

The XNA project templates include an integrated game loop, easy-to-use (and fast) methods to display graphics, full support for 3D models, and simple access to multiple types of input devices.

With the summer 2011 release of the XNA 4.0 Refresh, Microsoft has provided what has been cited as both the most requested feature for XNA and the most requested feature of Visual Basic developers: the ability to use Visual Basic as the backend for coding XNA projects.

Tip

What does XNA stand for, anyway?

According to the developers, XNA is an acronym for "XNA's Not Acronymed".

In this introductory chapter, you will:

  • Look at an overview of the games presented in this book

  • Download and install the Windows Phone Developers Tools, which includes the Visual Studio Express and the XNA Extensions for Visual Studio

  • Create a new Windows game project

  • Modify the default Windows Game template to build your first XNA game

Overview of the games


Many beginning developers make the mistake of attempting to tackle far too large a project early on. Modern blockbuster video games are the result of the efforts of hundreds of programmers, designers, graphics artists, sound effects technicians, producers, directors, actors, and many other vocations, often working for years to create the game.

That does not mean that the efforts of a solo developer or small team need to be dull, boring, and unplayable. This book is designed to help you develop a solid understanding of 2D game development with XNA Game Studio. By the time you have completed the projects in this book, you will have the necessary knowledge to create games that you can complete without an army of fellow game developers at your back.

In this chapter, you will build your first XNA mini-game, chasing squares around the screen with your mouse cursor. In subsequent chapters, the following four more detailed games are presented:

  • Flood Control: An explosion in one of the research laboratories has cracked the pressure dome protecting your underwater habitat. Work quickly to construct a series of pipes to pump water out of the habitat, before it floods. Flood Control is a board-based puzzle game with simple game mechanics and slowly increasing difficulty.

  • Asteroid Belt Assault: After being separated from your attack fleet in hyperspace, you find yourself lost in an asteroid field without communications or navigation systems. Work your way through the chaos of the asteroid belt while combating alien pilots intent upon your destruction. A vertically-scrolling space shooter, Asteroid Belt Assault introduces scrolling backgrounds, along with player and computer-controlled characters.

  • Robot Rampage: In the secret depths of a government defense facility, a rogue computer has taken control of robotic factories across the world, constructing an army of mechanical soldiers. Your mission—infiltrate these factories and shut down their network links to break the computer's control. A multi-axis shooter utilizing both of the analog control sticks on the Xbox 360 gamepad controller, Robot Rampage generates and manages dozens of on-screen sprites, and introduces world map construction.

  • Gemstone Hunter: Explore the Australian wilderness, abandoned mines, and ancient caves in a search for fabulous treasures. In Gemstone Hunter, you will construct a classic platform-style game, including a Windows Forms-based level editor and a multi-map "world" to challenge the player.

The games are each presented over two chapters. In the first chapter, the basics are implemented to the point where the game is playable. In the second chapter, features and polish are added to the game.

Each game introduces both new concepts and expands on topics covered in the previous games. At the end of each game chapter, you will find a list of exercises challenging you to use your newly-gained knowledge, to enhance previous games in the book.

We will focus on Windows as our platform for the games presented in this book. That said, the code presented in this book requires very little in the way of changes for other XNA platforms, generally only requiring implementation of platform-specific controls (gamepads, touch screen, and so on), and consideration of the differences in display sizes and orientation on non-Windows devices.

System requirements


In order to develop games using XNA Game Studio, you will need a computer capable of running both Visual Studio 2010 and the XNA Framework extensions. The general requirements are listed in the following table:

Component

Minimum requirement

Notes

Operating System

Windows Vista SP2 or Windows 7 (all editions except Starter)

As of XNA 4.0, Windows XP is no longer officially supported.

Graphics Card

Shader Model 1.1 support and DirectX 9.0 support

Microsoft recommends Shader Model 2.0 support as it is required for many of the XNA Starter Kits and code samples. The projects in this book similarly require Shader Model 2.0 support.

Development Platform

Visual Studio 2010 or Visual Studio 2010 Express

You will install Visual Studio 2010 Express as part of the XNA installation later in this chapter.

Optional requirements

Windows Phone

Windows Phone Development Tools, DirectX 10 or later, Compatible Video Card

Development tools include a Windows Phone emulator to test applications, without deployment to a physical device.

Xbox Live

Xbox Live Silver membership and XNA Creator's Club Premium membership

Xbox Live Silver is free. The XNA Creator's Club Premium membership costs $49 for 4 months or $99 for 1 year.

Installing XNA Game Studio


To get started developing games in XNA, you will need to download and install the software. You will need both Visual Studio and XNA extensions. With the release of XNA 4.0, the install packages have been consolidated, and both required components are included in the Windows Phone SDK package. The SDK was previously known as the Windows Phone Developers Tools prior to the release of the XNA 4.0 Refresh as part of the Windows Phone SDK 7.1 update.

Tip

XNA and the Windows Phone SDK

The October 2010 release of the Windows Phone 7 platform marked a shift in Microsoft's direction for XNA. Prior to Windows Phone, XNA was a separate download that included Visual C# Express. While still supporting the Windows and Xbox platforms as well as the Windows Phone, XNA is no longer available separately, and has been rolled into the Windows Phone SDK.

Time for action – installing XNA Game Studio


  1. Visit http://create.msdn.com/en-us/home/getting_started, and download the latest version of the Windows Phone SDK package. Run the setup wizard and allow the installation package to complete.

  2. Open Visual Studio 2010 Express. Click on the Help menu and select Register Product. Click on the Register Now link to go to the Visual Studio Express registration page. After you have completed the registration process, return to Visual Studio 2010 Express and enter the registration number into the registration dialog box.

  3. Close Visual Studio 2010 Express.

  4. Launch Visual Studio 2010 Express, and the Integrated Development Environment (IDE) will be displayed, as shown in the following screenshot:

Tip

Other versions of Visual Studio and XNA

Different versions of Visual Studio and XNA can be installed on the same PC, without interfering with each other. If you wish to target the Zune platform, you will need to install Visual Studio 2008 Express and XNA 3.1 (which only supports the C# language). Additionally, Visual Studio Express and Visual Studio Professional can co-exist on the same PC, and XNA will integrate with both of them, if the Windows Phone SDK is installed after Visual Studio.

What just happened?

You have now successfully installed the Windows Phone SDK, which includes Visual Studio 2010 Express, the XNA Extensions for Visual Studio, and the re-distributable Font Pack provided by Microsoft for XNA developers.

Building your first game


XNA attempts to simplify many of the basic elements of game development by automatically handling things, such as the game update loop and presenting the current frame of graphical information to the display. To illustrate just how much of the background work is integrated into the XNA project templates, let's jump in straight away and create your first game within a few minutes of finishing the installation.

Tip

Visual Basic versus C# - tutorials and samples on the web

With a five-year headstart on Visual Basic developers, there are a host of XNA tutorials, code samples, and forum posts written for C# out on the Internet. In the interest of being able to utilize these resources, I will occasionally point out topics or sections of code and their equivalent in C# notation.

In SquareChase, we will generate randomly positioned squares of different colors while the user attempts to catch them with their mouse pointer before they disappear. While building the project, we will discuss each of the major code sections pre-defined by the XNA templates.

Time for action – creating a new Windows game project


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

  2. Under Project Type, make sure Visual Basic is selected as the language and that the XNA Game Studio 4.0 category is selected.

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

  4. Name the project SquareChase (this will automatically update the Solution Name).

  5. Click on OK.

What just happened?

Each of the XNA project templates is a series of files and settings that get copied to your new project folder. Included in this set of files is the Game1.vb file, which is the heart of your XNA game.

Tip

Back up your projects

When you create your project, the Location field specifies where it will be saved. By default, Visual Studio creates a folder in your user documents area called Visual Studio 2010 to store both programs and configuration information. Under this folder is a Projects folder that contains subfolders for each new project you create. Make backups of your projects on a regular basis. You do not want to lose your hard work to a disk failure!

Anatomy of an XNA game

The most basic XNA game will have all of its code contained in the file called Game1.vb. This file is generated when you create a new project and contains override declarations for the methods used to manage your game. In addition to the Game1 class' declarations area, there are five primary methods that you will customize for any XNA project.

The declarations area

Right below the class declaration for Game1 is the class level declarations area. By default, this area contains two variables:

Private WithEvents graphics As GraphicsDeviceManager
Private WithEvents spriteBatch As SpriteBatch

The graphics object provides access to, not surprisingly, the system's video card. It can be used to alter the video mode, the size of the current viewport (the area that all drawing work will be clipped to if specified), and retrieve information about Shader Models the video card supports.

XNA provides the SpriteBatch class to allow you to (very quickly) draw 2D images (called sprites) to the screen. The spriteBatch variable is an instance of this class, which we will use for all of our drawing purposes in SquareChase.

The declarations area is the spot for any variables that need to be maintained outside of any of the individual methods discussed next, such as LoadContent, Update, and Draw. In practice, any data that you need to keep track of throughout your game will be referenced in some way in your declarations section.

Time for action – adding variables to the class declaration area


  1. Right below the Private WithEvents spriteBatch As SpriteBatch line, add the following:

    Private rand As New Random()
    Private squareTexture As Texture2D
    Private currentSquare As Rectangle
    Private playerScore As Integer
    Private timeRemaining As Single
    Private Const TimePerSquare As Single = 0.75
    Private colors() As Color = {Color.Red, Color.Green, Color.Blue}

Tip

Downloading the example code and colored images

You can download the example code files and the colored images for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

What just happened?

These are all the variables you will need for the SquareChase MINI-GAME. Here is a quick breakdown:

  • rand: This instance of the Random class is used to generate random numbers through the Next() method. You will use this to generate random coordinates for the squares that will be drawn to the screen.

  • squareTexture: The Texture2D class holds a 2D image. We will define a small texture in memory to use when drawing the square.

  • currentSquare: The XNA Framework defines a structure called Rectangle that can be used to represent an area of the display, by storing the x and y position of the upper-left corner along with a width and height. SquareChase will generate random squares and store the location in this variable.

  • playerScore: Players will score one point each time they successfully "catch" a square by clicking on it with their mouse. Their score accumulates in this integer variable.

  • timeRemaining: When a new square is generated, this float will be set to a value representing how many seconds it will remain active. When the counter reaches zero, the square will be removed and a new square generated.

  • TimePerSquare: This constant is used to set the length of time that a square will be displayed before it "runs away" from the player.

  • colors: This array of Color objects will be used when a square is drawn to cycle through the three colors in the array. The Color structure identifies a color by four components: red, green, blue, and alpha. Each of these components can be specified as a byte from 0 to 255, representing the intensity of that component in the color. Alpha represents how transparent the color is, allowing things already drawn behind it to show through. XNA drawing functions utilize pre-multiplied alpha, meaning that the alpha value has already been reflected in the other components of the color. We can accomplish this by simply creating a color with an RGB value and multiplying it by the desired alpha level we wish (between 0.0 and 1.0).

Tip

Data types

If your experience with Visual Basic is primarily VBScript-related, you may not be used to specifying data types (integer, single, Texture2D, and so on) to your variables. VBScript uses a generic "Variant" type that is interpreted by the runtime into a type that makes sense for what you are trying to do with it.

By contrast, Visual Basic .NET requires that your variables specify a data type that determines how they are allocated in memory and what you can use them for. In the case of SquareChase, we are using two basic data types:

Integer: It is a whole-number value between -2,147,483,648 and 2,147,483,647. This is equivalent to the C# type "int".

Single: This is a floating-point number. The numeric range for Singles depends on the digits of precision specified. This is equivalent to the C# type "float".

The Game1 class constructor

The XNA templates define an instance of the Microsoft.Xna.Framework.Game class with the default name Game1 as the primary component of your new game. Slightly more goes on behind the scenes, as we will see when we add an XNA game to a Windows form in Chapter 8, Gemstone Hunter: Put on your Platform Shoes, but for now, we can consider the Game1 constructor as the first thing that happens when our XNA game is executed. The class constructor is identified as Public Sub New(), and by default, the constructor contains only two lines:

graphics = New GraphicsDeviceManager(Me)
Content.RootDirectory = "Content"

For most of the games in this book, we will not need to make extensive modifications to the Game1 constructor, as its only job is to establish a link to the GraphicsDeviceManager object, and set the default directory for the Content object, which is used to load images, sound, and other game content.

Tip

Objects, classes, and methods

Many of the items that we define in our code will be classes. A Class is logical grouping of data and code. There are many built-in classes in Visual Basic and XNA, including things such as Integer and SpritBatch. Our Game1 file is itself a class definition, based on the XNA Game class. We can define new classes either from scratch, or based on existing classes. When they are based on other classes, they are said to inherit from a base class. We create instances of our class in order to use them, called objects. In the previous code snippet, the graphics object is assigned a new instance of the GraphicsDeviceManager class.

The code portions of an object are called Methods. In Visual Basic, methods are either Subs or Functions. A class can have a special Sub called New, which is the class constructor. When an instance of the class is created, the constructor is run and can be passed values to initialize the new object to a known state.

The Initialize() method

After the constructor has finished and your XNA game begins to run, the Initialize() method is called. This method only runs once, and the default code created with a new project template simply calls the base version of the method. The Initialize() method is the ideal place to set up features, such as screen resolution, toggling full screen mode, and enabling the use of a mouse in a Windows project. Other game objects that do not rely on external content, such as graphics and sound resources, can also be initialized here.

Time for action – customizing the Initialize() method


  1. Add the following before the call to MyBase.Initialize():

    Me.IsMouseVisible = True

What just happened?

By default, the mouse is not visible inside the XNA game window. Setting the IsMouseVisible property of the running instance of the Game1 class enables the mouse cursor in Windows.

Tip

Input types on other platforms

The Xbox and Windows Phone do not have mice, so what happens when the code to enable the mouse runs on these platforms? Nothing! If a platform is not equipped to support a specific type of input, the request just returns the default values when no input is being received. It is also safe to ask other platforms about their non-existent keyboards and check the state of a gamepad on a Windows PC without one attached.

The LoadContent() method

Part of the responsibility of the base Initialize() method is to call LoadContent() when the normal initialization has completed. The method is used to read in any graphical and audio resources your game will need. The default LoadContent() method is also where the spriteBatch object gets initialized. You will use the spriteBatch instance to draw objects to the screen during execution of the Draw() method.

Time for action – creating the squareTexture


  1. Open Microsoft Paint or your favorite image editor, create a new 16 x16 pixel image, and fill it with white.

  2. Save the image as "SQUARE.BMP" in a temporary location.

  3. Back in Visual Studio, right-click on SquareChaseContent (Content) in Solution Explorer (you may need to scroll down to see it) and select Add | Existing Item. Browse to the image you created and click on Ok.

  4. Add the following code to the LoadContent() method after the spriteBatch initialization:

    squareTexture = Content.Load(Of Texture2D)("SQUARE")

What just happened?

To load content, it must first exist. In steps 1 and 2 mentioned previously, you created a bitmap image for the square texture. In step 3, you added the bitmap image as a piece of content to your project.

Tip

Powers of two

Very old graphics cards required that all texture images be sized to "powers of two" (2, 4, 8, 16, 32, 64, 128, 256, and so on). This limitation is largely non-existent with modern video hardware, especially for 2D graphics. In fact, the sample code in the XNA Platform Starter Kit uses textures that do not conform to the "powers of two" limitation. In our case, the size of the image we create is not critical, as we will be scaling the output when we draw squares to the screen.

Finally, in step 4, you used the Content instance of the ContentManager class to load the image from disk and into memory when your game runs. The Content object is established automatically by XNA for you when you create a new project. When we add content items, such as images and sound effects to our game project, the XNA Content Pipeline converts our content files into an intermediate format that we can read through the Content object. These XNB files get deployed alongside the executable for our game to provide their content data at runtime.

The Content object's Load() method requires us to specify what kind of data we are loading by including Of along with the data type in parenthesis before the parameters that are passed to the method. In this case, the content we are loading is a Texture2D, which represents a 2D image. Finally, we specify the asset name of the item we wish to load from the content project. The default asset name is the same as the filename, without the file extension.

Tip

Asset names

If you create subdirectories inside your Content project (as we will do in the other games in this book), the asset name will include the path to the file. If our square.bmp file were in a directory called Textures, the asset name would be "Textures\Square".

The Update() method

Once LoadContent() has finished doing its job, an XNA game enters an endless loop in which it attempts to call the Update() method 60 times per second. This default update rate can be changed by setting the TargetElapsedTime property of the Game1 object, but for our purposes, the default time step will be fine. If your Update() logic begins taking too long to run, your game will begin skipping calls to the Draw() method in favor of multiple calls to Update(), to attempt to catch up to the current game time.

All of your game logic gets built into the Update() method. It is here that you check for player input, move sprites, spawn enemies, track scores, and everything else except draw to the display. Update() receives a single parameter called gameTime, which can be used to determine how much time has elapsed since the previous call to Update() or to determine if your game is skipping Draw() calls by checking its IsRunningSlowly property.

The default Update() method contains code to exit the game if the player presses the Back button on the first gamepad controller.

Tip

Exiting a game under Windows

The default Update() code provides anyone with a gamepad a way to end the game, but what if you do not have a gamepad? Press Alt + F4 on the keyboard or click on the standard Windows close button to exit your game when running in Windows.

Time for action – coding Update() for SquareChase


  1. Add the following to Update() method right before MyBase.Update(gameTime):

    If (timeRemaining = 0.0) Then
      currentSquare = New Rectangle(rand.Next(0, Me.Window.ClientBounds.Width - 25),rand.Next(0, Me.Window.ClientBounds.Height - 25),25, 25)
      timeRemaining = TimePerSquare
    End If
    Dim mouseInfo As MouseState = Mouse.GetState()
    If (mouseInfo.LeftButton = ButtonState.Pressed) And(currentSquare.Contains(mouseInfo.X, mouseInfo.Y)) Then
      playerScore += 1
      timeRemaining = 0.0
    End If
    timeRemaining = MathHelper.Max(0, timeRemaining -CType(gameTime.ElapsedGameTime.TotalSeconds, Single))
    Me.Window.Title = "Score : " & playerScore.ToString()

What just happened?

The first thing the Update() routine does is check to see if the current square has expired, by checking to see if timeRemaining has been reduced to zero. If it has, a new square is generated using the Next() method of the rand object. In this form, Next() takes two parameters: an (inclusive) minimum value and a (non-inclusive) maximum value. In this case, the minimum is set to 0, while the maximum is set to the size of the Me.Window.ClientBounds property minus 25 pixels. This ensures that the square will always be fully within the game window.

The square that is generated represents both the location and size of the square that we will draw shortly. Because we are drawing a solid color, the texture and the square do not need to be the same size. When we draw the square, XNA will stretch the 16x16 texture to fill the 25x25 square. If we were drawing a detailed image instead of a colored square, we would need to take this scaling into account to avoid visual artifacts or odd stretching when drawing the texture.

Next, the current position and button state of the mouse is captured into the mouseInfo variable through Mouse.GetState(). Both the Keyboard and the GamePad classes also use a GetState() method that captures all of the data about that input device when the method is executed.

Tip

Visual Basic versus C# - variable naming

C# is a case-sensitive language, so if we were to declare variables named "mouse", "Mouse" and "MOUSE", they would all represent different objects in memory. Visual Basic is case-insensitive, meaning that all three of these identifiers refer to the same variable. In fact, Visual Studio will change them all to match the way you type it when it is first declared in your code.

It is common in C# to use a lower-case variable of the same name as the class or structure you are creating an instance of, so in C# "mouse=Mouse.GetState();" would be perfectly acceptable, but it would be problematic in Visual Basic. You might notice that the XNA template itself does this in a few cases (spriteBatch, gameTime), which are carried over from their C# counterparts. This ends up working out, because the SpriteBatch and GameTime classes do not have any methods or properties that can be accessed outside of an instance of the classes, while Mouse does.

If the mouse reports that the left button is pressed, the code checks with the currentSquare object by calling its Contains() method to determine if the mouse's coordinates fall within its area. If they do, then the player has "caught" the square and scores a point. The timeRemaining counter is set to 0, indicating that the next time Update() is called, it should create a new square.

After dealing with the user input, the MathHelper.Max() method is used to decrease timeRemaining by an amount equal to the elapsed game time, since the last call to Update(). Max() is used to ensure that the value does not go below zero.

Finally, the game window title bar is updated to display the player's score.

Tip

MathHelper

The Microsoft.Xna.Framework namespace provides a class called MathHelper that contains lots of goodies to make your life easier when dealing with numeric data, including converting degrees to and from radians, clamping values between a certain range, and generating smooth arcs between a starting and ending value.

The Draw() method

The final method in the default Game1.vb file is responsible, not surprisingly, for drawing the current game state to the display. Draw() is normally called once after each call to Update(), unless something is happening to slow down the execution of your game. In that case, Draw() calls may be skipped in order to call Update() more frequently. There will always be at least one call to Update() between calls to Draw(), however, as sequential Draw() calls would provide no benefit—nothing in the game state will have changed.

The default Draw() method simply clears the display window to the Cornflower Blue color.

Time for action – draw SquareChase!


  1. Alter the GraphicsDevice.Clear(Color.CornflowerBlue) call and replace Color.CornflowerBlue with Color.Gray to make the game a bit easier on the eyes.

  2. Add the following code after the call to clear the display:

    spriteBatch.Begin()
    spriteBatch.Draw(
      squareTexture,
      currentSquare,
      colors(playerScore Mod 3))
    spriteBatch.End()

What just happened?

Any time you use a SpriteBatch object to draw to the display, you need to wrap the calls inside a Begin() and End() pair. Any number of calls to spriteBatch.Draw() can be included in a single batch, and it is common practice to simply start a Begin() at the top of your Draw() code, use it for all of your drawing, and then End() it right before the Draw() method exits. While not benefiting our SquareChase game, batching sprite drawing calls greatly speeds up the process of drawing a large number of images, by submitting them to the rendering system all at once instead of processing each image individually.

The SpriteBatch.Draw() method is used to draw a Texture2D object to the screen. There are a number of different options for how to specify what will be drawn. In this case, the simplest call requires a Texture2D object (squareTexture), a destination Rectangle (currentSquare), and a tint color to apply to the sprite. The expression "playerScore Mod 3" takes the player's score, divides it by 3, and returns the remainder. The result will always be 0, 1, or 2. This fits perfectly as an index to the elements in the colors array, allowing us to easily change the color of the square each time the player catches one.

Finally, the spriteBatch.End() tells XNA that we have finished queuing up sprites to draw and it should actually push them all out to the graphics card.

Time for action – play SquareChase!


  1. Run your game by clicking on Start Debugging from the Debug menu or hitting F5 on the keyboard.

  2. Play an exciting game of SquareChase, by holding down the mouse button and trying to catch the squares with your mouse cursor:

What just happened?

You just finished your first XNA game, that's what!

Granted, it is not exactly the next blockbuster, but at only around 30 lines of code, it implements a simple game mechanic, user input, score tracking and display, and clock-based timing. Not bad for a few minutes' work.

Have a go hero

As simple as it is, here are a couple of enhancements you could make to SquareChase:

  • Vary the size of the square, making it smaller every few times the player catches one, until you reach a size of 10 pixels.

  • Start off with a higher setting for TimePerSquare and decrease it a little each time the player catches a square (hint: you'll need to remove the Const declaration in front of TimePerSquare if you wish to change it at runtime).

Summary


You now have a development environment set up for working on your XNA game projects, including Visual Studio 2010 Express and the XNA 4.0 Refresh extensions.

We also saw how the XNA game loop initializes, executes, and constructs an elementary game by expanding on the default methods provided by the Windows Game template.

It is time to dive headfirst into game creation with XNA. In the next chapter, we will begin building the puzzle game Flood Control in which the player is challenged to pump water out of their flooding underwater research station before the entire place really is underwater!

Left arrow icon Right arrow icon

Key benefits

  • Visual Basic edition of Kurt Jaegers' XNA 4.0 Game Development by Example. The first book to target Visual Basic developers who want to develop games with the XNA framework
  • Dive headfirst into game creation with Visual Basic and the XNA Framework
  • Four different styles of games comprising a puzzler, space shooter, 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

Description

XNA Game Studio enables hobbyists and independent game developers to easily create video games, and now gives that power to Visual Basic developers. XNA lets you bring your creations to life on Windows, the Xbox 360 and the Windows Phone platforms. The latest release of XNA has added support to Visual Basic and therefore, Visual Basic developers now have the power to give life to their creativity with XNA.This book covers both the concepts and the implementations necessary to get you started on bringing your own creations to life with XNA. It presents four different games, including a puzzler, space shooter, multi-axis shoot 'em up, and a jump-and-run platformer. Each game introduces new concepts and techniques to build a solid foundation for your own ideas and creativity.This book details the creation of four games, all in different styles, from start to finish using Visual Basic and the Microsoft XNA framework. 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 Visual Basic would be needed to kickstart your game development.

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
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 : Dec 23, 2011
Length: 424 pages
Edition : 1st
Language : English
ISBN-13 : 9781849692403

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 : Dec 23, 2011
Length: 424 pages
Edition : 1st
Language : English
ISBN-13 : 9781849692403

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.0 Game Development by Example: Beginner's Guide - Visual Basic Edition
$48.99
Microsoft XNA 4.0 Game Development Cookbook
$54.99
XNA 4 3D Game Development by Example: Beginner's Guide
$54.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.8
(10 Ratings)
5 star 80%
4 star 20%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




LabRat Mar 18, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very good examples and really like that it addresses visual basic. Hope author comes out with a 3D version for VB also.
Amazon Verified review Amazon
C. Moeller May 02, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book is aimed towards beginners starting out in game programming. Visual basic is one of the easier languages to get started in, and XNA is a well known game framework, so it is an excellent place for beginners to start.The book starts out with an introduction to XNA, and how to set it up on your machine for development. The author explains everything he adds to the code, which makes it easy to understand what each addition does.The first game is created in chapter 2, so the author quickly gets into actually creating games fairly quickly, while introducing important concepts such as sprite sheets and tile based games.The following games continue to introduce important concepts, from collision detection to the A* pathfinding algorithm, and even using a map editor to make levels for a side scrolling mario-esque game!I would definitely recommend this book to beginner and intermediate game programmers. The amount of important concepts introduced in this book would give you a great start to developing more advanced games in the future, and the concepts will still be useful for any 3d games. It doesn't matter so much what language you start out programming, just learning the game programming concepts will get you started regardless of what language you eventually choose to develop in.
Amazon Verified review Amazon
Pedro Guida Feb 07, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Based on its C# sibling , this book brings a great introduction to XNA 4.0 for devs that use Visual Basic as their primary language.Targeting beginners, the author introduces useful concepts and techniques applicable to both, game development per se and XNA 4.0, through four games: a puzzler, a space shooter, a multi-axis shoot 'em up and a jump-and-run platformer.All code presented is fully explained by the Author and explanations are written clearly and simple, so each chapter is easy to follow.To wrap it up: fully explained, easy to understand and with four different game examples, the book is a must have for VB devs that want to take their first steps on the XNA world.
Amazon Verified review Amazon
LP Apr 30, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
XNA originally required the novice programmer to learn a few new concepts all at the same time theXNA Framework, .Net, C# together with many programming and maths concepts required in created2D and 3D games. Jumping directly into C# itself was a tall order especially when one already learnsother languages at school / college such as Visual Basic (VB). This is possibly why the most requestedfeature for XNA was to enable support for Visual Basic.This book does not dwell on the pros or cons of C# v VB for development, and assumes that thereader has already made this choice, otherwise why read the book. It is for each novice programmerto decide which programming language is more suited to them and if undecided it may make senseto use this book orientated to VB and compare it with its sister book XNA 4.0 Game Development byExample, orientated to C#. They use the same sample programs and are so a good way to determinewhich is easier to learn for each individual.As a novice programmer the first thing you should do is download the complimentary source codethat is available from the publisher's web site. This book is not a typing tutorial and so it is alwaysbetter to load the code for each sample.As I was already familiar with the actual example programs I skipped through most of their detail,and concentrated mainly on the differences between C# and VB, mainly to fill in my own knowledgeof what had occurred in VB since my last venture with VB6.I continue to like the books editing style with detailed explanations of each step with regularsections of `What just happened?' . This makes it easy to distinguish the stepped explanations fromthe general content for each chapter.I must again highlight the excellent explanations for path finding using the A* algorithm. This topic isessential for every game programmer eventually.Having read the book it failed to convert me from C# to VB, but that was not its objective.If you are a novice programmer and still undecided whether to follow the C# or VB route what betterway than to acquire both the VB and the C# version of this book can decide for yourself whichlanguage suits your existing knowledge.
Amazon Verified review Amazon
Code Monkey Mar 04, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
XNA is a fantastic platform for developing rich, immersive, robust experiences for gamers on Windows, Windows Phone, and Xbox consoles. The platform has been long the domain of C# developers only. That has now changed with the advent of the XNA Game Studio for Visual Basic.This book offers an excellent rundown of the capabilities of Visual Basic on the platform and provides superb step by step examples of how to complete some of the most essential parts of game design.The examples are clear and well thought out and the author does an excellent job of walking the developer through the process. This is done at a high enough level for beginners while still offering enough information and material for developers that have previously worked on the platform.The book's an excellent read and a great tool for learning the platform if you are a VB developer. With the breadth of the examples, it is a fantastic reference tool that will be a good fit for any developers technical library.
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