XNA 4.0 Game Development by Example: Beginner's Guide - Kurt Jaegers - E-Book

XNA 4.0 Game Development by Example: Beginner's Guide E-Book

Kurt Jaegers

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

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

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 477

Veröffentlichungsjahr: 2010

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

XNA 4.0 Game Development by Example Beginner's Guide
Credits
About the Author
About the Reviewers
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Time for action – heading
What just happened?
Have a go hero – heading
Reader feedback
Customer support
Errata
Piracy
Questions
1. Introducing XNA Game Studio
Overview of the games
System requirements
Installing XNA Game Studio
Time for action – installing XNA Game Studio
What just happened?
Building your first game
Time for action – creating a new Windows game project
What just happened?
Anatomy of an XNA game
The declarations area
Time for action – adding variables to the class declaration area
What just happened?
The Game1 class constructor
The Initialize() method
Time for action – customizing the Initialize() method
What just happened?
The LoadContent() method
Time for action – creating the squareTexture
What just happened?
The Update() method
Time for action – coding Update() for SquareChase
What just happened?
The Draw() method
Time for action – draw SquareChase!
What just happened?
Time for action – play SquareChase!
What just happened?
Have a go hero
Summary
2. Flood Control – Underwater Puzzling
Designing a puzzle game
Time for action – set up the Flood Control project
What just happened?
Introducing the Content Pipeline
Time for action – reading textures into memory
What just happened?
Sprites and sprite sheets
Classes used in Flood Control
The GamePiece class
Identifying a GamePiece
Time for action – build a GamePiece class – declarations
What just happened?
Creating a GamePiece
Time for action – building a GamePiece class: constructors
What just happened?
Updating a GamePiece
Time for action – GamePiece class methods – part 1 – updating
Rotating pieces
Time for action – GamePiece class methods – part 2 – rotation
What just happened?
Pipe connectors
Time for action – GamePiece class methods – part 3 – connection methods
Sprite sheet coordinates
Time for action – GamePiece class methods – part 4 – GetSourceRect
What just happened?
The GameBoard class
Time for action – create the GameBoard.cs class
What just happened?
Creating the game board
Time for action – initialize the game board
What just happened?
Updating GamePieces
Time for action – manipulating the game board
What just happened?
Filling in the gaps
Time for action – filling in the gaps
What just happened?
Generating new pieces
Time for action – generating new pieces
What just happened?
Water filled pipes
Time for action – water in the pipes
What just happened?
Propagating water
Time for action – making the connection
What just happened?
Building the game
Declarations
Time for action – Game1 declarations
What just happened?
Initialization
Time for action – updating the Initialize() method
What just happened?
The Draw() method – the title screen
Time for action – drawing the screen – the title screen
What just happened?
The Draw() method – the play screen
Time for action – drawing the screen – the play screen
What just happened?
Keeping score
Time for action – scores and scoring chains
What just happened?
Input handling
Time for action – handling mouse input
What just happened?
Letting the player play!
Time for action – letting the player play
What just happened?
Play the game
Summary
3. Flood Control – Smoothing Out the Rough Edges
Animated pieces
Classes for animated pieces
Time for action – rotating pieces
What just happened?
Time for action – falling pieces
What just happened?
Time for action – fading pieces
What just happened?
Managing animated pieces
Time for action – updating GameBoard to support animatedpieces
What just happened?
Fading pieces
Time for action – generating fading pieces
What just happened?
Falling pieces
Time for action – generating falling pieces
What just happened?
Rotating pieces
Time for action – modify Game1 to generate rotating pieces
What just happened?
Calling UpdateAnimatedPieces()
Time for action – updating Game1 to update animated pieces
What just happened?
Drawing animated pieces
Time for action – update Game1 to draw animated pieces
What just happened?
SpriteBatch overloads
SpriteFonts
Time for action – add SpriteFonts to Game1
What just happened?
Score display
Time for action – drawing the score
What just happened?
ScoreZooms
Time for action – creating the ScoreZoom class
What just happened?
Time for action – updating and displaying ScoreZooms
What just happened?
Adding the GameOver game state
Time for action – game over
What just happened?
The flood
Time for action – tracking the flood
What just happened?
Displaying the flood
Time for action – displaying the flood
What just happened?
Difficulty levels
Time for action – adding difficulty levels
What just happened?
Have a go hero
Summary
4. Asteroid Belt Assault – Lost in Space
Creating the project
Time for action – creating the Asteroid Belt Assault project
What just happened?
Another definition for "sprite"
Building the Sprite class
Time for action – declarations for the Sprite class
What just happened?
Time for action – Sprite constructor
What just happened?
Time for action – basic Sprite properties
What just happened?
Time for action – animation and drawing properties
What just happened?
Collision detection
Time for action – supporting collision detection
What just happened?
Animation and movement
Time for action – adding animation frames
What just happened?
Time for action – updating the Sprite
What just happened?
Time for action – drawing the Sprite
What just happened?
A sprite-based star field
Time for action – creating the StarField class
What just happened?
Time for action – updating and drawing the StarField
What just happened?
Time for action – viewing the StarField in action
What just happened?
Animated sprites – asteroids
Time for action – building the AsteroidManager class
What just happened?
Positioning the asteroids
Time for action – positioning the asteroids
What just happened?
Time for action – checking the asteroid's position
What just happened?
Time for action – updating and drawing asteroids
What just happened?
Colliding asteroids
Time for action – bouncing asteroids – part 1
What just happened?
Time for action – bouncing asteroids – part 2
What just happened?
Player and enemy shots
Time for action – adding the ShotManager class
What just happened?
Time for action – firing shots
What just happened?
Time for action – updating and drawing shots
What just happened?
Adding the player
Time for action – creating the PlayerManager class
What just happened?
Handling user input
Time for action – handling user input
What just happened?
Time for action – updating and drawing the player's ship
What just happened?
Enemy ships
Time for action – creating the Enemy class
What just happened?
Time for action – waypoint management
What just happened?
Time for action – enemy update and draw
What just happened?
The EnemyManager class
Time for action – creating the EnemyManager class
What just happened?
Managing waypoints
Time for action – setting up the EnemyManager class
What just happened?
Time for action – spawning enemies
What just happened?
Time for action – updating and drawing the EnemyManager
What just happened?
Summary
5. Asteroid Belt Assault – Special Effects
Explosion effects
Expanding on sprites – particles
Time for action – constructing the Particle class
What just happened?
Time for action – updating and drawing particles
What just happened?
Particle explosions
Time for action – the ExplosionManager class
What just happened?
Time for action – creating explosions
What just happened?
Time for action – updating and drawing explosions
What just happened?
The collision manager
Time for action – creating the CollisionManager class
What just happened?
Handling collisions
Time for action – player shot collisions
What just happened?
Time for action – player collisions
What just happened?
Time for action – using the CollisionManager class
What just happened?
Sound effects
Generating and finding sound effects
Sound in XNA
Time for action – building a sound effects manager
What just happened?
Time for action – using the SoundManager class
What just happened?
The game structure
Time for action – structuring the game
What just happened?
Time for action – drawing the game structure
What just happened?
Have a go hero
Summary
6. Robot Rampage – Multi-Axis Mayhem
Statics, statics, everywhere
Time for action – creating the Robot Rampage project
What just happened?
A world larger than the screen
Defining a camera
Time for action – creating the Camera class
What just happened?
World-aware sprites
Time for action – building a new Sprite class
What just happened?
Visualizing the view
Time for action – viewing the Sprite and Camera classes in action
What just happened?
The game world – tile-based maps
Tiles
The tile map
Time for action – creating the TileMap class
What just happened?
Map squares
Time for action – dealing with map squares
What just happened?
Dealing with tiles
Time for action – handling tiles
What just happened?
Drawing the map
Time for action – drawing the tile map
What just happened?
Generating a random map
Time for action – random wall placement
What just happened?
Adding the player
Building the Player class
Time for action – building the Player class
What just happened?
Moving around the world
Time for action – handling input
What just happened?
Staying in bounds
Time for action – staying in bounds
What just happened?
Running into tiles
Time for action – accounting for walls
What just happened?
Summary
7. Robot Rampage – Lots and Lots of Bullets
Visual effects
Revisiting particles
Time for action – the Particle class
What just happened?
The EffectsManager class
Time for action – the EffectsManager class
What just happened?
Time for action – building explosions
What just happened?
Time for action – spark effects
What just happened?
Adding weaponry
The WeaponManager class
Time for action – beginning the WeaponManager class
What just happened?
Weapon upgrades
Time for action – new weapons
What just happened?
Shot to map collisions
Time for action – shots colliding with tiles
What just happened?
Power-ups
Time for action – power-ups
What just happened?
We still have a problem...
Path finding
The A* path-finding algorithm
Implementing A*
Time for action – the PathNode class
What just happened?
Time for action – beginning the implementation of A*
What just happened?
Time for action – finding the path
What just happened?
Time for action – adjacent squares
What just happened?
Safely placing power-ups
Time for action – updating the WeaponManager class
What just happened?
Player goals
Computer terminals
Time for action – building a computer terminal
What just happened?
Spawning computer terminals
Time for action – the GoalManager class
What just happened?
Enemy robots
Enemy basics
Time for action – building the Enemy class
What just happened?
Moving enemies
Time for action – enemy AI methods
What just happened?
The enemy manager
Time for action – the enemy manager
What just happened?
Updating the WeaponManager
Time for action – destroying enemies
What just happened?
Game structure
Time for action – the GameManager class
What just happened?
Keeping score
Time for action – awarding points
What just happened?
Updating Game1
Time for action – updating the Game1 class
What just happened?
Have a go hero
Summary
8. Gemstone Hunter – Put on Your Platform Shoes
Borrowing graphics
Time for action – creating projects
What just happened?
A more advanced tile engine
Time for action – the MapSquare class
What just happened?
Rebuilding the camera
Time for action – the Camera class
What just happened?
Constructing the tile engine
Time for action – the TileMap class – part 1
What just happened?
Time for action – the TileMap class – part 2
What just happened?
Drawing the tile map
Time for action – the TileMap class – part 3
What just happened?
Time for action – adding the tile map to the game project
What just happened?
The map editor project
Creating the map editor project
Time for action – creating the level editor project
What just happened?
Adding a form
Time for action – adding a form
What just happened?
Time for action – adding event handlers
What just happened?
Filling Out Our Form
Time for action – creating the menu bar
What just happened?
Time for action – tile selection controls
What just happened?
Time for action – scroll bars
What just happened?
Time for action – final controls
What just happened?
Updating the Game1 class
Time for action – updating Game1
What just happened?
Time for action – the Game1 Update method
What just happened?
Connecting the form to the game
Time for action – completing the editor – part 1
What just happened?
Time for action – fixing the scrolling delay
What just happened?
Loading and Saving Maps
Time for action – implementing loading and saving
What just happened?
Passability
Map codes
One last issue
Time for action – handling the FormClosed event
What just happened?
Have a go hero
Summary
9. Gemstone Hunter – Standing on Your Own Two Pixels
Animation strips
Time for action – building the Animation class
What just happened?
Animated game objects
Time for action – building the GameObject class – Part 1
What just happened?
Drawing, animation, and movement
Time for action – building the GameObject class – part 2
What just happened?
Map-based collision detection
Time for action – building the GameObject class – part 3
What just happened?
The Player
Time for action – creating the Player class
What just happened?
Running...
Time for action – overriding the Update() method – part 1
What just happened?
...and jumping
Time for action – overriding the Update() method – part 2
What just happened?
Staying on the screen
Time for action – repositioning the camera
What just happened?
Loading levels
The LevelManager class
Time for action – building the LevelManager class
What just happened?
Gemstones
Time for action – building the Gemstone class
What just happened?
Scoring
Time for action – implementing score tracking
What just happened?
Enemies
Time for action – summoning up the zombies
What just happened?
Player-enemy interaction
Time for action – interacting with zombies
What just happened?
Level transitions
Time for action – supporting map transitions
What just happened?
Processing other codes
Time for action – handling codes
What just happened?
Game structure
Time for action – implementing game states
What just happened?
Have a go hero
Summary
Index

XNA 4.0 Game Development by Example Beginner's Guide

XNA 4.0 Game Development by Example Beginner's Guide

Copyright © 2010 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: September 2010

Production Reference: 1180910

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN 978-1-84969-066-9

www.packtpub.com

Cover Image by Vinayak Chittar (<[email protected]>)

Credits

Author

Kurt Jaegers

Reviewers

Rodolfo Rigo Calabrezi

Dustin Heffron

Alexandre Ribeiro de Sá

Acquisition Editor

David Barnes

Development Editor

Wilson D'souza

Technical Editor

Dayan Hyames

Copy Editor

Laxmi Subramanian

Indexers

Hemangini Bari

Monica Ajmera Mehta

Editorial Team Leader

Aditya Belpathak

Project Team Leader

Ashwin Shetty

Proofreaders

Jacqueline McGhee

Chris Smith

Graphics

Nilesh R. Mohite

Production Coordinator

Arvindkumar Gupta

Cover Work

Arvindkumar Gupta

About the Author

Kurt Jaegers is a database administrator by day, and a long-time hobbyist game developer, having built games for everything from the Commodore 64 to the Xbox 360. He is the owner of xnaresources.com, one of the earliest XNA-focused tutorial websites.

I would like to thank my wife Linda for proofreading the earliest versions of this book, as well as my brother Jason for providing the graphics for Flood Control, Asteroid Belt Assault, and the map tiles for Gemstone Hunter, along with the title screens for all of the games.

I would also like to thank the team at Packt Publishing for guiding me through my first book-authoring experience.

About the Reviewers

Rodolfo Rigo Calabrezi has worked in desktop publishing and web advertising campaigns, PC and mobile applications, critical systems and web 2.0 frontend. In the 90s, he made games for the MSX and TRS-Color platforms. In 2004, he worked as the CTO at Eleven Cells, a game development studio. He built an impressive professional network. He was a member of IGDA, working directly on programming, game design, art production, and QA. He teaches and gives lectures in schools about game development. He is in charge of Quantix Games, a Brazilian game development studio. He knows PHP, HTML, CSS, JavaScript, C/C++, C#, HLSL, engine architecture, graphics pipeline, ODE, Ageia, Direct3D, OpenGL, Jupiter, Cipher, PopCap, HGE, XNA, and Flash and is learning UDK and Unity. For DCC, he works with Photoshop, Flash, modo, Reason, and Nuendo, and is learning XSI and Maya. He is familiar with the following platforms—PC, PocketPC, Amiga, Xbox 360, and PS2, and is new to iPhone and iPad.

He is interested in development for other console platforms like PS3, Nintendo Wii, and DS.

Dustin Heffron is an avid gamer and programmer. He graduated in 2010 from Penn State University with a Bachelor's of Science degree in Computer Science. He has had 7+ years of experience programming in various languages and environments, including all C-based languages and most .NET languages. He has worked with XNA since 2007 and applied it in a variety of military and video game related projects.

Currently, Dustin works for the Applied Research Lab at Penn State as a Graphical User Interface programmer and Acid Lab Studios as Lead Programmer. He is planning on releasing his first episodic commercial game, "The Scarab Gauntlet" in late 2010, with additional episodes to follow.

I would like to thank my boss Mitch Lebold for giving me the opportunity to research and apply XNA to a variety of real-world projects. Without this experience, I wouldn't be the developer I am today. I would also like to thank Andy Strauch, producer and founder of Acid Lab Studios for giving me the opportunity to program such a great game and being patient with me during the busier times of life. Lastly, I would like to thank Packt Publishing for letting me review this insightful book, which I've greatly enjoyed reading.

Alexandre Ribeiro de Sá is a Producer, Director, Programmer and self-proclaimed frustrated artist. Alexandre was present in many game development community websites in Brazil giving support in translation and writing articles about software development and CG. Today as a producer, programmer, and sometimes as a game designer in his own game studio, the Vortex Game Studios in São Paulo, Brazil, he works with outsourcing and in his own games titles for computer and video game consoles.

Preface

The Microsoft XNA Framework provides a powerful set of tools to allow development teams of any size, from the individual developer to larger independent teams, to rapidly develop high performance quality games for multiple Microsoft-related platforms.

This book will present a series of video games, utilizing XNA Game Studio and the XNA Framework to delve into the world of 2D game development targeting the Microsoft Windows environment. We will utilize XNA's 2D graphics capabilities to present our games to the player, and look at the fundamental systems behind several game design challenges, such as path-finding, collision detection, special effects, and more.

Each of the four games in this book cover a new gaming style, and introduce progressively more advanced techniques and systems to provide a foundation for bringing your own creations to life.

What this book covers

Chapter 1, Introducing XNA Game Studio begins by looking at the history of the XNA Framework and its predecessors, and installing the Windows Phone Development Tools package that includes the version 4.0 release of the XNA tools. We wrap up this chapter by looking at the building blocks of an XNA game and putting together an XNA mini-game called SquareChase.

Chapter 2, Flood Control – Underwater Puzzling introduces a board-based puzzle game called Flood Control. We introduce the XNA Content Pipeline, and build a recursive function to determine the state of the game board while playing.

Chapter 3, Flood Control – Smoothing out the Rough Edges refines and completes the Flood Control game, adding animated rotation, movement, and fading of game pieces. We will implement a scoring system and cover displaying text to the screen.

Chapter 4, Asteroid Belt Assault – Lost in Space begins developing our second game. This time we put together a space-based shooter. We will create a basic moving star field using a simple particle system, and introduce frame-based sprite animation. We will add moving asteroids to our star field and examine how to detect collisions between asteroids and make them respond realistically. We add a player-controlled spaceship, and enemies that can fly across the screen following pre-defined waypoints.

Chapter 5, Asteroid Belt Assault – Special Effects wraps up Asteroid Belt Assault. We implement collision detection between the player, enemies, asteroids, and bullets and create particle-based explosions. Finally, we will look at loading and playing sound effects to bring life to our in-game events.

Chapter 6, Robot Rampage – Multi-Axis Mayhem begins the construction of a tank-based game in which the player can move and fire independently using either an Xbox 360 controller or the keyboard. We build a tile-map based game world and a camera class to view a screen-sized area of the larger world, and implement player collision with the walls of the tile map.

Chapter 7, Robot Rampage – Lots and Lots of Bullets completes Robot Rampage by expanding on our particle-based explosion system, and adding enemies, player goals, and weapon upgrades to our tile map. We allow the player to fire at the enemies with several different weapons. Finally, we create an implementation of the A* path-finding algorithm to allow the enemy tanks to track down the player.

Chapter 8, Gemstone Hunter – Put on your Platform Shoes introduces a side-scrolling, jump-and-run platform game. We start by evolving our tile-based mapping system to allow multiple layers of tiles, and look at combining XNA and Windows Forms to produce a map editor for Gemstone Hunter. As part of this process, we will look at building more complex solutions that contain multiple projects, and separate our game's tile engine into a Game Library project.

Chapter 9, Gemstone Hunter – Standing on Your Own Two Pixels concludes the Gemstone Hunter project by examining an alternative method for frame-based sprite animation using player and enemy graphics from the XNA Platform Starter Kit. We implement platform physics and bring the game together by loading levels and reacting to their embedded code values.

What you need for this book

In order to install and use the Microsoft XNA 4.0 tools, you will need a Windows PC with either Microsoft Windows Vista or Microsoft Windows 7, and a video card supporting DirectX 9 or later. Shader Model 1.1 is required for XNA, but it is highly recommended that your video card support Shader Model 2.0 or later, as many of the XNA samples available online require 2.0 support.

Who this book is for

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

Conventions

In this book, you will find several headings appearing frequently.

To give clear instructions of how to complete a procedure or task, we use:

Time for action – heading

Action 1Action 2Action 3

Instructions often need some extra explanation so that they make sense, so they are followed with:

What just happened?

This heading explains the working of tasks or instructions that you have just completed.

You will also find some other learning aids in the book, including:

Have a go hero – heading

These set practical challenges and give you ideas for experimenting with what you have learned.

You will also find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: "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."

A block of code is set as follows:

spriteBatch.Begin(); spriteBatch.Draw( squareTexture, currentSquare, colors[playerScore % 3]); spriteBatch.End();

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Run your game by clicking on Start Debugging from the Debug menu".

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Tip

Downloading the example code for this book

You can download the example code files 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.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Introducing XNA Game Studio

With the release of Windows 95, Microsoft also introduced the DirectX Application Programming Interface (API), which allowed Windows-based applications to integrate closely, in a standard way, with the graphics hardware available on the system. Prior to DirectX, most PC game development targeted MS-DOS, as Windows-based graphics were too slow for most gaming needs.

Although faster, working with the DirectX API could be challenging. The DirectX Software Development Kit (SDK) is targeted at C++, with no official support for other languages. The developer is also faced with large volumes of background work to get a DirectX project to the point where he can display images on the screen before ever considering the logic of the game itself.

In 2002, Microsoft released Managed DirectX as an interface to the API from its new .NET development environment. The .NET Framework consists of a set of code libraries to perform common programming tasks, and the Common Language Runtime (CLR) which allows code written in the various .NET languages (including Visual Basic .NET and C#) to be compiled into common runtime code. In order to support devices such as Windows Mobile phones, a subset of the .NET Framework was released, called the .NET Compact Framework. The .NET CF, as it is often abbreviated, removed non-essential components of the full Framework in the interest of saving storage space on handheld devices.

While Managed DirectX 2.0 was still in the beta phase, the project was cancelled, and Microsoft XNA was introduced in its place. XNA consists of the XNA Framework, a set of code libraries to perform common graphics, sound, and other game related tasks, and XNA Game Studio, an extension of the Visual Studio C# 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.

In addition to Windows games, XNA allows deployment to both the Xbox 360, the Zune handheld media player (with XNA 3.1) and Windows Phone 7 Series phones (with XNA 4.0). For the first time, a game console manufacturer has released a supported method for individual game developers to create (and sell!) content for their game console. Microsoft has even established the Xbox Indie Games system on Xbox Live to allow you to sell your creations to the world.

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 bookDownload and install XNA Game StudioCreate a new Windows Game projectModify 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, graphic 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 knowledge necessary 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 Hyper Space, 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 defence 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 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 C# 2010 Express and the XNA Framework extensions. The general requirements are:

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

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.

Optional requirements

Windows Phone

DirectX 10 or later, Compatible Video Card

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

Zune platform

Zune Software 3.0 or higher, Visual C# 2008, XNA Game Studio 3.1

Only required if you plan to deploy games to a Zune handheld device. Zune development is supported under XNA 3.1.

Xbox Live

Xbox Live Silver membership, 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.

Tip

HiDef vs. Reach

As of version 4.0, XNA now supports two different rendering profiles. The HiDef profile is available on the Xbox 360 and Windows PCs with DirectX 10 or better video cards, and uses Shader Model 3.0. The Reach profile is available on all XNA platforms, and uses Shader Model 2.0. If you have a DirectX 9 video card, or wish to distribute your games to computers with DirectX 9 support, you will need to right-click on your project in Solution Explorer and select Properties. On the XNA Game Studio tab, select the Reach profile.

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 C# and XNA Game Studio. With the release of XNA 4.0, the install packages have been consolidated, and both required components are included in the Windows Phone Developer Tools package.

Time for action – installing XNA Game Studio

Visit http://www.microsoft.com/express/Phone/ and download the Windows Phone Developer Tools package. Run the setup wizard and allow the installation package to complete.Open Visual Studio 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 Express and enter the registration number into the registration dialog box.Close Visual Studio Express.Download the Font Pack from http://go.microsoft.com/fwlink/?LinkId=104778.Extract the ZIP file contents to a temporary folder (leave this folder open).From the Start Menu, select Control Panel. Under Classic View, choose Fonts.Drag the fonts from the temporary folder to the Fonts folder.Close both Explorer windows.Launch Visual Studio Express, and the Integrated Development Environment (IDE) will be displayed as seen 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 C# 2008 Express and XNA 3.1. Additionally, Visual Studio Express and Visual Studio Professional can coexist on the same PC, and XNA will integrate with both of them if it is installed after Visual Studio.

What just happened?

You have now successfully installed the Windows Phone Developers Tools, including XNA Game Studio 4.0 and the Redistributable Font Pack provided by Microsoft for XNA developers.

Tip

The redistributable fonts package

To use its integrated text drawing methods, XNA games need to convert normal Windows fonts into an internal format called a SpriteFont. These SpriteFonts get distributed with your game, which means you will not be able to use most of the fonts on your computer due to licensing restrictions. For this reason, Microsoft has provided a selection of fonts that XNA developers can freely distribute without purchasing an individual license to do so.

Building your first game

XNA attempts to simplify many of the basic elements of game development by handling things like the game update loop and simplifying the display of graphical objects. 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.

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

In the Visual C# window, open the File menu and select New Project...Under Project Type, make sure XNA Game Studio 4.0 is selected.Under Templates, select Windows Game (4.0).Name the project SquareChase (This will automatically update the Solution Name).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.cs file, which is the heart of your XNA game.

Tip

Backup 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.cs. 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 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:

GraphicsDeviceManager graphics; SpriteBatch 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 declarations area is the spot for any variables that need to be maintained outside of any of the individual methods listed below. In practice, any data you need to keep track of throughout your game will be referenced, in some way, in your declarations section.

Time for action – draw SquareChase!

Alter the GraphicsDevice.Clear(Color.CornflowerBlue); call and replace Color.CornflowerBlue with Color.Gray to make the game a bit easier on the eyes.Add the following code after the call to clear the display:
spriteBatch.Begin(); spriteBatch.Draw( squareTexture, currentSquare, colors[playerScore % 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 % 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!

Run your game by clicking on Start Debugging from the Debug menu or hit F5 on the keyboard.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 33 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 Express and XNA Game Studio 4.0.

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

It is time to dive head first 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!

Chapter 2. Flood Control – Underwater Puzzling

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

This chapter focuses on the following concepts:

Using the Content Pipeline to load textures from diskCreating classes to divide code into logical unitsRecursively evaluating the status of the game board to check for scoring chainsDrawing textures using the SpriteBatch.Draw() methodManaging simple game states

Designing a puzzle game

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

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