XNA 4.0 Game Development by Example: Beginner's Guide - Visual Basic Edition

By Kurt Jaegers
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Introducing XNA Game Studio

About this book

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.

Publication date:
December 2011
Publisher
Packt
Pages
424
ISBN
9781849692403

 

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!

About the Author

  • Kurt Jaegers

    Kurt Jaegers is an Oracle Database Administrator and Windows Network Administrator, as well as a long-time hobbyist game developer. He has built games for everything from the Commodore 64 to the Xbox 360. He is the owner of xnaresources.com, and the author of XNA 4.0 Game Development by Example: Beginner's Guide (C# edition) and XNA 4.0 Game Development by Example: Beginner's Guide – Visual Basic Edition, both of which were published by Packt Publishing.

    Browse publications by this author
Book Title
Access this book, plus 7,500 other titles for FREE
Access now