Creating a Graphical User Interface

Creating the GUI Controls

A graphical user interface (GUI) is absolutely essential for a game to be successful, even if that means using nothing more than labels and buttons on the screen that the user can click on.

Sprite Class Improvements

Modifying the Sprite Class

To make the GUI controls more effective, the Sprite class must be tweaked just a little.

  1. We need to change the definition of p_content and p_spriteBatch from private to protected so that they will be accessible to classes that inherit from Sprite. This way, we can load assets and draw without creating new reference variables in every subclass. Open the Sprite class and make the change:
    [code]
    protected ContentManager p_content;
    protected SpriteBatch p_spriteBatch;
    [/code]
  2. Just to be sure we are on the same page despite the changes made to this class in the past, here is the Load() method. Ignore past changes and just note this current version, which shows that the size and origin properties have been moved out of the try block:
    [code]
    public virtual bool Load(string assetName)
    {
    try
    {
    image = p_content.Load<Texture2D>(assetName);
    }
    catch (Exception) { return false; }
    size = new Vector2(image.Width, image.Height);
    origin = new Vector2(image.Width / 2, image.Height / 2);
    return true;
    }
    [/code]
  3. Add an error-handling line to the Draw() method so that it won’t crash the program if the image is null. This is a common verification. Since our GUI controls will be using a few images in interesting ways, we just want to ensure that any image that is not loaded correctly won’t crash the program—instead, it will just not show up.
    [code]
    public virtual void Draw()
    {
    if (!visible) return;
    if (image == null) return;
    . . .
    }
    [/code]

GUI Base Class: Control

All the GUI classes will be found in the GUI.cs source code file for the sake of convenience. Within that file, the classes will be wrapped inside the GameLibrary namespace (the same namespace used by Sprite and Animation).

[code]
namespace GameLibrary
{
. . .
}
[/code]

The base GUI class is called Control, and it is primarily used to create a reference to the ContentManager, SpriteBatch, and SpriteFont objects used in a game—all of which are needed by the GUI. Control inherits from Sprite, so it supplies GUI controls (declared as subclasses of Control) with all the features of Sprite, including loading and drawing. Methods are declared as virtual or override so they can be used and overridden in each subclass. There are certainly more services the base class could provide, such as touch input, but it turns out (during development) that most of that code must reside in each individual class. Listing 20.1 contains the source code for the Control class.

LISTING 20.1 Source Code for the Control Class

[code]
public abstract class Control : Sprite
{
protected SpriteFont p_font;
public Control(ContentManager content, SpriteBatch spriteBatch,
SpriteFont font)
: base(content, spriteBatch)
{
p_font = font;
}
public override bool Load(string filename)
{
return base.Load(filename);
}
public virtual void Update(TouchLocation touch)
{
}
public override void Draw()

{
base.Draw();
}
}
[/code]

Label Control

A Label is the most fundamental type of GUI control, with the simple task of displaying a text message on the screen. This is more important than it might at first seem, because a Label control can be moved anywhere on the screen without affecting the call to Label.Draw() from the main program. This Label class is rather basic, providing a shadow feature with customizable Color properties for the text and shadow. Two Labels will be used in the sample project later in this hour. Listing 20.2 contains the source code for the Label class.

LISTING 20.2 Source Code for the Label Class

[code]
public class Label : Control
{
public string text;
public Color shadowColor;
public Color textColor;
public bool UseShadow;
public Label(ContentManager content, SpriteBatch spriteBatch,
SpriteFont font)
: base(content, spriteBatch, font)
{
text = ““;
color = Color.White;
textColor = Color.White;
shadowColor = Color.Black;
UseShadow = true;
}
public override void Update(TouchLocation touch)
{
base.Update(touch);
}
public override void Draw()
{
if (UseShadow)
{
p_spriteBatch.DrawString(p_font, text,
new Vector2(position.X – 2, position.Y – 2), shadowColor);
}
p_spriteBatch.DrawString(p_font, text, position, textColor);
}
public Vector2 TextSize()
{
return p_font.MeasureString(text);
}
}
[/code]

Button Control

A Button is the second most common type of control needed for a rudimentary GUI system. Our Button class will load a 64×64 bitmap file called button.png (which must be in the content project). The great thing about this is that you can replace the image with one of your own. Due to the way the class works, I recommend using an image with the same dimensions but with your own “skin” theme. The button used in the example this hour is a gray box with a white outline. An important feature for a Button control is to display text and respond to user tap events. Our Button goes further by allowing its background and text colors to be changed independently for a customized look. Listing 20.3 contains the source code for the Button class.

LISTING 20.3 Source Code for the Button Class

[code]
public class Button : Control
{
public string text;
public Color shadowColor;
public Color textColor;
public bool UseShadow;
public bool Tapped;
public Button(ContentManager content, SpriteBatch spriteBatch,
SpriteFont font)
: base(content, spriteBatch, font)
{
text = ““;
color = Color.White;
textColor = Color.White;
shadowColor = Color.Black;
UseShadow = true;
Load(“button”);
}
public override void Update(TouchLocation touch)
{
base.Update(touch);
Tapped = false;
if (touch.State == TouchLocationState.Pressed)
{
Rectangle rect = Boundary();
Vector2 pos = touch.Position;
Point point = new Point((int)pos.X, (int)pos.Y);
if (rect.Contains(point))
{
Tapped = true;
}
}
}
public override void Draw()
{
base.Draw();
Vector2 size = TextSize();
Vector2 pos2 = new Vector2(position.X + 2, position.Y + 2);
Vector2 pivot = new Vector2(size.X / 2, size.Y / 2);
p_spriteBatch.DrawString(p_font, text, position, shadowColor,
0.0f, pivot, 1.0f, SpriteEffects.None, zindex);
p_spriteBatch.DrawString(p_font, text, pos2, textColor, 0.0f, pivot,
1.0f, SpriteEffects.None, zindex);
}
public Vector2 TextSize()
{
return p_font.MeasureString(text);
}
}
[/code]

Horizontal Slider Control

A slider control makes it possible to adjust a setting or to control some aspect of a game directly by the user, and resembles a movable sliding lever on the screen. There are two types of slider: horizontal and vertical. Although one common class could be used for both slider orientations, it would be more coding work, so it is more effective to just separate them into HSlider and VSlider controls. This is definitely a complex type of control compared to Label and Button. HSlider loads three images, so these bitmap files must all be found in the content project for the GUI code to run properly:

  • hslider_bar.png
  • hslider_end.png
  • button.png

Remember, when you are creating your own game using these GUI controls, that you can skin the controls to your own liking. The slider button needn’t be a circle at all! It can be any shape, including a custom image or a picture of a dragon—it doesn’t matter, and it’s up to you!

The left and right end images are shared, so if you create a custom skin for the control, be sure that the end images are interchangeable. The middle piece is a line one (1) pixel wide, scaled to the width of the control (set with the HSlider.Limit property). If the limit is 100, the one-pixel-wide image is scaled by 100 times to reach the edge! The scale as well as other properties are borrowed from the base Sprite class embedded in Control, inherited by HSlider. There isn’t much error handling, so if you try to set Limit to a negative number, it just will not work right or will crash. Listing 20.4 contains the source code for the HSlider class.

LISTING 20.4 Source Code for the HSlider Class

[code]
public class HSlider : Control
{
public bool Moving;
public Vector2 start;
private int p_value;
private int p_limit;
Sprite sprLeftEnd, sprRightEnd, sprBar;
public HSlider(ContentManager content, SpriteBatch spriteBatch,
SpriteFont font)
: base(content, spriteBatch, font)
{
scale = 1.0f;
start = Vector2.Zero;
Load(“slider_tab”);
sprLeftEnd = new Sprite(content, spriteBatch);
sprLeftEnd.Load(“hslider_end”);
sprLeftEnd.origin = new Vector2(3, 16);
sprRightEnd = new Sprite(content, spriteBatch);
sprRightEnd.Load(“hslider_end”);
sprRightEnd.origin = new Vector2(0, 16);
sprBar = new Sprite(content, spriteBatch);
sprBar.Load(“hslider_bar”);
sprBar.origin = new Vector2(0, 16);
Limit = 100;
}
public int Value
{
get { return p_value; }
set
{
p_value = value;
if (p_value < 0) p_value = 0;
if (p_value > p_limit) p_value = p_limit;
position.X = start.X + p_value;
}
}
public int Limit
{
get { return p_limit; }
set
{
p_limit = value;
sprBar.scaleV = new Vector2((float)
(p_limit + this.image.Width+1), 1.0f);
}
}
public override void Update(TouchLocation touch)
{
base.Update(touch);
Moving = false;
if (touch.State == TouchLocationState.Moved)
{
Rectangle rect = Boundary();
Point point = new Point((int)touch.Position.X,
(int)touch.Position.Y);
if (rect.Contains(point))
{
Vector2 relative = Vector2.Zero;
relative.X = touch.Position.X – position.X;
position.X += relative.X;
Value = (int)(position.X – start.X);
if (position.X < start.X)
position.X = start.X;
else if (p_value > p_limit)
position.X -= relative.X;
Moving = true;
}
}
}
public override void Draw()
{
//draw ends
sprLeftEnd.position = new Vector2(start.X – 16, start.Y);
sprLeftEnd.color = this.color;
sprLeftEnd.Draw();
sprRightEnd.position = new Vector2(start.X + 16 + p_limit, start.Y);
sprRightEnd.color = this.color;
sprRightEnd.Draw();
//draw middle bar
sprBar.position = new Vector2(start.X – 16, start.Y);
sprBar.color = this.color;
sprBar.Draw();
//draw sliding circle
base.Draw();
//draw value text
Vector2 size = p_font.MeasureString(p_value.ToString());
p_spriteBatch.DrawString(p_font, p_value.ToString(), position,
Color.Black, 0.0f, new Vector2(size.X/2, size.Y/2), 0.6f,
SpriteEffects.None, 1.0f);
}
public void SetStartPosition(Vector2 pos)
{
position = pos;
start = pos;
}
}
[/code]

Vertical Slider Control

The Vertical Slider control, or VSlider, shares all the same functionality as HSlider, but calculations are shifted 90 degrees in a vertical orientation. So, all the “X” properties used in the HSlider’s functionality become “Y” properties in VSlider in order for it to work properly. Here are the bitmaps required by the control (and note that button.png is shared):

  • vslider_bar.png
  • vslider_end.png
  • button.png

Listing 20.5 contains the source code for the VSlider class.

LISTING 20.5 Source Code for the VSlider Class

[code]
public class VSlider : Control
{
public bool Moving;
public Vector2 start;
private int p_value;
private int p_limit;
Sprite sprTopEnd, sprBottomEnd, sprBar;
public VSlider(ContentManager content, SpriteBatch spriteBatch,
SpriteFont font)
: base(content, spriteBatch, font)
{
scale = 1.0f;
start = Vector2.Zero;
Load(“slider_tab”);
sprTopEnd = new Sprite(content, spriteBatch);
sprTopEnd.Load(“vslider_end”);
sprTopEnd.origin = new Vector2(16, 3);
sprBottomEnd = new Sprite(content, spriteBatch);
sprBottomEnd.Load(“vslider_end”);
sprBottomEnd.origin = new Vector2(16, 0);
sprBar = new Sprite(content, spriteBatch);
sprBar.Load(“vslider_bar”);
sprBar.origin = new Vector2(16, 0);
Limit = 100;
}
public int Value
{
get { return p_value; }
set
{
p_value = value;
if (p_value < 0) p_value = 0;
if (p_value > p_limit) p_value = p_limit;
position.Y = start.Y + p_value;
}
}
public int Limit
{
get { return p_limit; }
set
{
p_limit = value;
sprBar.scaleV = new Vector2(1.0f, (float)
(p_limit + this.image.Height + 1));
}
}
public override void Update(TouchLocation touch)
{
base.Update(touch);
Moving = false;
if (touch.State == TouchLocationState.Moved)
{
Rectangle rect = Boundary();
Point point = new Point((int)touch.Position.X,
(int)touch.Position.Y);
if (rect.Contains(point))
{
Vector2 relative = Vector2.Zero;
relative.Y = touch.Position.Y – position.Y;
position.Y += relative.Y;
Value = (int)(position.Y – start.Y);
if (position.Y < start.Y)
position.Y = start.Y;
else if (p_value > p_limit)
position.Y -= relative.Y;
Moving = true;
}
}
}
public override void Draw()
{
//draw ends
sprTopEnd.position = new Vector2(start.X, start.Y – 16);
sprTopEnd.color = this.color;
sprTopEnd.Draw();
sprBottomEnd.position = new Vector2(start.X, start.Y + 16 + p_limit);
sprBottomEnd.color = this.color;
sprBottomEnd.Draw();
//draw middle bar
sprBar.position = new Vector2(start.X, start.Y – 16);
sprBar.color = this.color;
sprBar.Draw();
//draw sliding circle
base.Draw();
//draw value text
Vector2 size = p_font.MeasureString(p_value.ToString());
p_spriteBatch.DrawString(p_font, p_value.ToString(), position,
Color.Black, 0.0f, new Vector2(size.X / 2, size.Y / 2), 0.6f,
SpriteEffects.None, zindex);
}
public void SetStartPosition(Vector2 pos)
{
position = pos;
start = pos;
}
}
[/code]

Demonstrating the GUI Controls

The initialization code for a GUI demo or a game using GUI controls will always be much more involved and code-intensive than the processing code where the controls are updated and drawn, because there are so many properties involved in creating and customizing a nice-looking, interactive GUI. Our example this hour demonstrates a GUI with Labels, Buttons, HSliders, and VSliders, and is quite functional, as you can see in Figure 20.1. The source code for the GUI Demo program is found in Listing 20.6.

The example demonstrates labels, buttons, and sliders.
FIGURE 20.1 The example demonstrates labels, buttons, and sliders.

On the left is a vertical slider used to adjust the background color. Why? Just to show that the slider works and does something interesting. Maybe in a game a VSlider would be used to adjust the power level of a catapult or an artillery gun. Really, the use for these controls is up to the game’s designer and is just implemented by the programmer (or team). On the right side are three buttons labeled RED, GREEN, and BLUE. Beside each button is a slider.

Clicking a button changes the color component to a random value from 0 to 255, and automatically moves the slider to that location. The slider can also be moved manually, and this in turn will change the button’s color to reflect the change to that color component. The end result of all this color manipulation is seen in the small, unassuming Exit button at the lower-right corner of the screen. Note that the Limit property of both HSlider and VSlider changes its overall size and defines the limits of the sliding button. The three color sliders have a range of 0 to 255, whereas the smaller vertical slider has a range of 0 to 100.

LISTING 20.6 Source Code for the GUI Demo Program

[code]
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteFont font;
Random rand;
TouchLocation oldTouch;
Label lblTitle, lblColor;
Button[] buttons;
HSlider[] hsliders;
VSlider vslider;
Color bgcolor;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = “Content”;
TargetElapsedTime = TimeSpan.FromTicks(333333);
oldTouch = new TouchLocation();
rand = new Random();
bgcolor = Color.CornflowerBlue;
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
font = Content.Load<SpriteFont>(“WascoSans”);
lblTitle = new Label(Content, spriteBatch, font);
lblTitle.text = “Graphical User Interface Demo”;
lblTitle.position = new Vector2(400 – lblTitle.TextSize().X / 2, 0);
//create buttons
buttons = new Button[4];
buttons[0] = new Button(Content, spriteBatch, font);
buttons[0].text = “RED”;
buttons[0].position = new Vector2(400, 150);
buttons[0].textColor = Color.Red;
buttons[0].color = Color.DarkRed;
buttons[0].scaleV = new Vector2(1.5f, 1.0f);
buttons[1] = new Button(Content, spriteBatch, font);
buttons[1].text = “GREEN”;
buttons[1].position = new Vector2(400, 230);
buttons[1].textColor = Color.Green;
buttons[1].color = Color.DarkGreen;
buttons[1].scaleV = new Vector2(1.5f, 1.0f);
buttons[2] = new Button(Content, spriteBatch, font);
buttons[2].text = “BLUE”;
buttons[2].position = new Vector2(400, 310);
buttons[2].textColor = Color.Cyan;
buttons[2].color = Color.DarkCyan;
buttons[2].scaleV = new Vector2(1.5f, 1.0f);
buttons[3] = new Button(Content, spriteBatch, font);
buttons[3].text = “Exit”;
buttons[3].position = new Vector2(750, 450);
buttons[3].scaleV = new Vector2(1.2f, 0.8f);
//create horizontal sliders for color editing
hsliders = new HSlider[3];
hsliders[0] = new HSlider(Content, spriteBatch, font);
hsliders[0].SetStartPosition(new Vector2(500, 150));
hsliders[0].color = Color.Red;
hsliders[0].Limit = 255;
hsliders[1] = new HSlider(Content, spriteBatch, font);
hsliders[1].SetStartPosition(new Vector2(500, 230));
hsliders[1].color = Color.LightGreen;
hsliders[1].Limit = 255;
hsliders[2] = new HSlider(Content, spriteBatch, font);
hsliders[2].SetStartPosition(new Vector2(500, 310));
hsliders[2].color = Color.Cyan;
hsliders[2].Limit = 255;
//create vertical slider for bg color editing
vslider = new VSlider(Content, spriteBatch, font);
vslider.SetStartPosition(new Vector2(140, 170));
vslider.color = Color.Yellow;
vslider.Limit = 100;
//create label for slider
lblColor = new Label(Content, spriteBatch, font);
lblColor.text = “Background Color”;
lblColor.position = new Vector2( 140 – lblColor.TextSize().X/2,
100);
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back ==
ButtonState.Pressed)
this.Exit();
TouchCollection touchInput = TouchPanel.GetState();
if (touchInput.Count > 0)
{
TouchLocation touch = touchInput[0];
oldTouch = touch;
lblTitle.Update(touch);
UpdateButtons(touch);
UpdateSliders(touch);
vslider.Update(touch);
lblColor.Update(touch);
}
base.Update(gameTime);
}
void UpdateButtons(TouchLocation touch)
{
//update buttons
int tapped = -1;
for (int n = 0; n < buttons.Length; n++)
{
buttons[n].Update(touch);
if (buttons[n].Tapped) tapped = n;
}
//was a button tapped?
int c = rand.Next(256);
switch (tapped)
{
case 0:
buttons[0].color = new Color(c, 0, 0);
hsliders[0].Value = c;
break;
case 1:
buttons[1].color = new Color(0, c, 0);
hsliders[1].Value = c;
break;
case 2:
buttons[2].color = new Color(0, 0, c);
hsliders[2].Value = c;
break;
case 3:
this.Exit();
break;
}
}
void UpdateSliders(TouchLocation touch)
{
//update horizontal sliders
int moving = -1;
for (int n = 0; n < hsliders.Length; n++)
{
hsliders[n].Update(touch);
if (hsliders[n].Moving) moving = n;
}
switch(moving)
{
case 0:
buttons[0].color = new Color(hsliders[0].Value, 0, 0);
break;
case 1:
buttons[1].color = new Color(0, hsliders[1].Value, 0);
break;
case 2:
buttons[2].color = new Color(0, 0, hsliders[2].Value);
break;
}
//colorize Exit button based on colors
buttons[3].color = new Color(hsliders[0].Value,
hsliders[1].Value, hsliders[2].Value);
//update vertical slider
if (vslider.Moving)
{
bgcolor = Color.CornflowerBlue;
bgcolor.R -= (byte)vslider.Value;
bgcolor.G -= (byte)vslider.Value;
bgcolor.B -= (byte)vslider.Value;
}
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(bgcolor);
spriteBatch.Begin(SpriteSortMode.Deferred,
BlendState.AlphaBlend);
lblTitle.Draw();
foreach (Button b in buttons)
b.Draw();
foreach (HSlider hs in hsliders)
hs.Draw();
vslider.Draw();
lblColor.Draw();
spriteBatch.End();
base.Draw(gameTime);
}
void print(int x, int y, string text, Color color)
{
var pos = new Vector2((float)x, (float)y);
spriteBatch.DrawString(font, text, pos, color);
}
}
[/code]

Reading and Writing Files Using Storage, Windows Phone Isolated Storage

Using Windows Phone Isolated Storage

XNA potentially supports many storage devices across all the game systems it targets, but on the WP7, there is only one type: isolated storage. Any type of game asset can be imported into the Content Manager through an existing or user-created content importer, and this is the preferred way to read game data that does not change. For data that might change, such as generated data files or user-created game levels, or saved games, we can access the file system to stream data to our game from isolated storage. Any type of data file can be opened and written to or read from using Storage.IO classes, which we will learn about here. Since XML is recognized as a resource file by Content Manager, we will use XML for our example in this hour. XML has the benefit of being versatile and human readable at the same time. But binary and text files can be used as well.

Saving a Data File

We will first learn to create a new file in isolated storage and then read the data back out of the file afterward. The first thing that must be done is to add the library System.Xml.Serialization to the project via the references. The Serialization library makes it very easy to convert a class or struct into a file and read it back again without our having to decode the file manually (by setting individual properties one at a time). Let’s add it to the project.

Adding XML Support to the Project

  1. Right-click References in the Content project and choose Add Reference from the pop-up context menu.
  2. Locate the library called System.Xml.Serialization in the list, as shown in Figure 19.1.

    The System.Xml. Serialization library.
    FIGURE 19.1 The System.Xml. Serialization library.

Now that the reference is set, we can use XML files in the project more easily.

Isolated Storage

To access a file in isolated storage, we have to create a file object using the IsolatedStorageFile class:

[code]
IsolatedStorageFile storage =
IsolatedStorageFile.GetUserStoreForApplication();
[/code]

IsolatedStorageFile.GetUserStoreForApplication() is a rather verbose method that creates the new storage object with linkage to the application’s (or game’s) private storage area, making it available for accessing files, directories, and so on. If the object doesn’t need to be made global to the project, a shorthand declaration can be used:

[code]
var storage = IsolatedStorageFile.GetUserStoreForApplication();
[/code]

Creating a New Directory

Next, a required step must be taken: A directory must be created for the application to store files in. The private or isolated storage area has room for dictionary-style key/value data as well as SQL database tables, so we can’t just toss files in there like one large file system—we have to create a directory. If you don’t create a directory first, an exception error will occur when you try to create a new file. We will use the storage object to create a directory. The IsolatedStorageFile class has a method called DirectoryExists() that returns true if a passed directory exists. CreateDirectory() is used to create a new directory. So, if the directory doesn’t already exist, we want to create it:

[code]
const string directory = “StorageDemo”;
if (!storage.DirectoryExists(directory))
storage.CreateDirectory(directory);
[/code]

Creating a New File

Now, we can create a file inside the directory. First, we have to check to see whether the file exists. WP7 does not support the FileMode.CreateNew option, which is supposed to overwrite a file if it already exists. Trying to do this generates an exception error, even though it works on Windows and Xbox 360. So, we have to delete the file first before creating it again. Usually this is not a problem because savegame data tends to be rather simple for most games. If you are working on a large, complex game, like an RPG, and there’s a lot of data, of course the game might support multiple savegame files, and you’ll have a mini file manager built into the game. But we’re just learning the ropes here, so we’ll do it the simple way to get it working. We use the FileExists() and DeleteFile() methods to get rid of the old save file:

[code]
const string filename = directory + “\savegame.dat”;
if (storage.FileExists(filename))
storage.DeleteFile(filename);
[/code]

Now we’re ready to create a new savegame file and write data to it. This is done with the IsolatedStorageFileStream() class:

[code]
var fstream = new IsolatedStorageFileStream(
filename, FileMode.CreateNew, storage);
[/code]

The FileMode enumeration has these values:

  • CreateNew = 1
  • Create = 2
  • Open = 3
  • OpenOrCreate = 4
  • Truncate = 5
  • Append = 6

Writing Data to the File with Serialization

Although any type of data file can be created, XML is quite easy to use, and an entire class or struct variable (full of game data) can be written to the file with only a couple lines of code. If you want to just write binary or text data to the file, that will work also at this point, but it’s so much easier to use serialization! Here is a simple struct we can use for this example:

[code]
public struct SaveGameData
{
public string Name;
public int Score;
}
[/code]

A new SaveGameData variable is created and the two properties are filled with data. This is where you would store actual game data in the properties in order to restore the game to this gameplay state later when the savegame file is loaded:

[code]
savedata = new SaveGameData();
savedata.Name = “John Doe”;
savedata.Score = rand.Next(500, 5000);
[/code]

Now, to write the data to the file, we have to create an XmlSerializer object, and then write the serialized object out to the file:

[code]
XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));
serializer.Serialize(fstream, savedata);
[/code]

At this point, the file has been created and data has been written to it that was contained in the savedata struct variable.

Loading a Data File

Loading a serialized XML file is very similar to the writing process. Of course, you may read a simple text or binary file and parse the data if that is more suitable for your needs, but I’m using serialization and XML because it’s so easy and likely to be the approach most game developers take with WP7 savegame data. The same storage object is created, but we don’t need any of the code to create a directory or delete the existing file (obviously), so the code to load the savegame file is much simpler:

[code]
var storage = IsolatedStorageFile.GetUserStoreForApplication();
[/code]

Likewise, the IsolatedStorageFileStream object is created in the same way:

[code]
var fstream = new IsolatedStorageFileStream(
filename, FileMode.CreateNew, storage);
[/code]

There is a second way to create the fstream file object variable: by creating the object in a using statement and then adding code that uses the object in the bracketed code block:
[code]
using (var fstream = new IsolatedStorageFileStream(
filename, FileMode.Open, storage)) { }
[/code]

The XmlSerializer object is created in a similar manner:

[code]
XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));
[/code]

The only difference really is a call to Deserialize() instead of Serialize(), and this method returns our savegame data as an object:

[code]
data = (SaveGameData)serializer.Deserialize(fstream);
[/code]

Just for curiosity’s sake, here is what the XML file looks like that is created by our code. If you were to serialize a more complex data type, like a Vector4, then the parameters within that class or struct would become sub-items in the XML structure.

[code]
<?xml version=”1.0”?>
<SaveGameData xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xmlns:xsd=”http://www.w3.org/2001/XMLSchema”>
<Name>John Doe</Name>
<Score>1245</Score>
</SaveGameData>
[/code]

Creating the Storage Demo Example

We will go over a complete program that demonstrates how to save data to a save game file and then load it again, based on some rudimentary user input. Two buttons are created and displayed using our familiar Button class (which inherits from Sprite). This class requires a bitmap file called button.png, so be sure that it exists in the content project.

To verify that the example is working, we will want to run the program, save the data, close the program, and then rerun it and choose the load option to see that the data is still there. So, the example should read and write the data only when the user chooses to, not automatically. When the emulator is being used, exiting the program still preserves it in memory, but closing the emulator will erase all traces of the program and data files.

Closing the WP7 emulator will wipe the storage memory, including data files created by our example here, and any programs previously loaded from Visual Studio. But closing the program and rerunning it will reveal an intact file system. This happens because the emulator creates a new emulation state system when it is run, and that is not saved when it closes.

Figure 19.2 shows the output of the Storage Demo program.

The Storage Demo example shows how to read and write data.
FIGURE 19.2 The Storage Demo example shows how to read and write data.

Button Class

Just for the sake of clarity, Listing 19.1 shows the source code for the Button class. We have seen the code before, but it is required by the Storage Demo and is included again for clarity.

LISTING 19.1 Source Code for the Button Class

[code]
public class Button : Sprite
{
public string text;
private SpriteBatch p_spriteBatch;
private SpriteFont p_font;
public Button(ContentManager content, SpriteBatch spriteBatch,
SpriteFont font)
: base(content, spriteBatch)
{
p_spriteBatch = spriteBatch;
p_font = font;
Load(“button”);
text = ““;
color = Color.LightGreen;
}
public void Draw()
{
base.Draw();
Vector2 size = p_font.MeasureString(text);
Vector2 pos = position;
pos.X -= size.X / 2;
pos.Y -= size.Y / 2;
p_spriteBatch.DrawString(p_font, text, pos, color);
}
public bool Tapped(Vector2 pos)
{
Rectangle rect = new Rectangle((int)pos.X, (int)pos.Y, 1, 1);
return Boundary().Intersects(rect);
}
}
[/code]

Storage Demo Source

Here in Listing 19.2, we have the source code for the Storage Demo program, with the definition of the SaveGameData class as well.

LISTING 19.2 Source Code for the Storage Demo Program

[code]
public struct SaveGameData
{
public string Name;
public int Score;
}
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteFont font;
Random rand;
TouchLocation oldTouch;
Button[] buttons;
int current = -1;
bool loaded = false;
SaveGameData savedata;
const string directory = “StorageDemo”;
const string filename = directory + “\savegame.dat”;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = “Content”;
TargetElapsedTime = TimeSpan.FromTicks(333333);
oldTouch = new TouchLocation();
rand = new Random();
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
font = Content.Load<SpriteFont>(“WascoSans”);
//create save button
buttons = new Button[2];
buttons[0] = new Button(Content, spriteBatch, font);
buttons[0].text = “Save”;
buttons[0].position = new Vector2(100, 100);
//create load button
buttons[1] = new Button(Content, spriteBatch, font);
buttons[1].text = “Load”;
buttons[1].position = new Vector2(300, 100);
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back ==
ButtonState.Pressed)
this.Exit();
//get state of touch input
TouchCollection touchInput = TouchPanel.GetState();
if (touchInput.Count > 0)
{
TouchLocation touch = touchInput[0];
if (touch.State == TouchLocationState.Pressed)
{
current = -1;
int n = 0;
foreach (Button b in buttons)
{
int x = (int)touch.Position.X;
int y = (int)touch.Position.Y;
if (b.Boundary().Contains(x, y))
{
current = n;
break;
}
n++;
}
}
oldTouch = touch;
}
if (current == 0)
{
savedata = new SaveGameData();
savedata.Name = “John Doe”;
savedata.Score = rand.Next(500, 5000);
SaveData(savedata);
loaded = false;
current = -1;
}
else if (current == 1)
{
savedata = LoadData();
loaded = true;
current = -1;
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin(SpriteSortMode.FrontToBack,
BlendState.AlphaBlend);
print(0, 0, “Storage Demo”, Color.White);
foreach (Button b in buttons)
b.Draw();
if (loaded)
{
print(100, 200, “Loaded data:nn” +
“Name: “ + savedata.Name + “n” +
“Score: “ + savedata.Score.ToString() + “n”,
Color.White);
}
spriteBatch.End();
base.Draw(gameTime);
}
void print(int x, int y, string text, Color color)
{
var pos = new Vector2((float)x, (float)y);
spriteBatch.DrawString(font, text, pos, color);
}
private void SaveData(SaveGameData data)
{
var storage = IsolatedStorageFile.GetUserStoreForApplication();
//create directory for data
if (!storage.DirectoryExists(directory))
storage.CreateDirectory(directory);
//delete any existing file
if (storage.FileExists(filename))
storage.DeleteFile(filename);
//create new savegame file
using (var fstream = new IsolatedStorageFileStream(filename,
FileMode.CreateNew, storage))
{
XmlSerializer serializer = new XmlSerializer(
typeof(SaveGameData));
serializer.Serialize(fstream, data);
}
}
private SaveGameData LoadData()
{
SaveGameData data;
var storage = IsolatedStorageFile.GetUserStoreForApplication();
using (var fstream = new IsolatedStorageFileStream(filename,
FileMode.Open, storage))
{
XmlSerializer serializer = new XmlSerializer(
typeof(SaveGameData));
data = (SaveGameData)serializer.Deserialize(fstream);
}
return data;
}
}
[/code]

We now have the ability to create a savegame file and load it again! This greatly enhances the replay value of a game that would otherwise appear to have been freshly installed every time it is run. Use this feature to store game settings, player names, and high score lists, as well as generated game levels and anything else that needs to be remembered by the game for the next time.

Playing Audio, Windows Phone Audio

Getting Started with Windows Phone Audio

The audio system in XNA makes it possible to reproduce sound effects and music in two different ways, but the WP7 platform supports only one of them. First, we can play audio clips directly from audio files loaded at runtime, with support for the most common audio file formats. Second, in XNA, we can use Microsoft’s Cross-Platform Audio Creation Tool, also known as XACT, which is more often used for complex games with many audio files. The first approach involves loading and managing audio objects in our own code. The second approach leaves the details largely up to classes provided for working with XACT resources built at compile time and then made available from a container of objects. But we can’t use XACT with WP7 projects, so we’ll learn about the first and only option instead. We’ll cover the audio system in the Microsoft.Xna.Framework.Audio namespace with an example of the audio system.

Simple Audio Playback

There is one very easy way to get audio to play in an XNA project: by using the SoundEffect class. There is a drawback to using SoundEffect assets that really can’t be avoided: the tendency for the content project to become cluttered with asset files. Even so, the SoundEffect class is convenient and easy to use. A helper class called SoundEffectInstance is also used in conjunction with SoundEffect for audio playback. SoundEffect itself has a Play() method, but it is rudimentary. SoundEffectInstance.Play() is more capable and versatile.

Adding Audio Content

Before we can play an audio clip, we have to add it to the content system.

  1. First, right-click the Content project in Solution Explorer, choose Add, and then choose Existing Item, as shown in Figure 18.1. This opens the Add Existing File dialog box.

    Adding an existing audio file to the content project.
    FIGURE 18.1 Adding an existing audio file to the content project.
  2. Locate the audio file you want to add to the project. Select the file in the file browser and click the OK button.

Loading an Audio Asset File

The following audio file types can be added to an XNA project for use with the SoundEffect class, but remember that WP7 does not support XACT:

  • XAP
  • WAV
  • WMA
  • MP3

You can create an instance of the SoundEffect class with a variable declared in the globals section at the top of the class as follows:

[code]
SoundEffect clip;
[/code]

The SoundEffect object is created in the usual LoadContent() function where all other asset files are loaded:

[code]
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
font = Content.Load<SpriteFont>(“Arial”);
clip = Content.Load<SoundEffect>(“sound_clip”);
}
[/code]

Playing an Audio Clip

The audio clip can be played back using the SoundEffect.Play() method. There is a simple version of Play() and an overloaded version, which gives you control over the Volume, Pitch, and Pan properties. The audio clip is played directly from the object like so:

[code]
clip.Play();
[/code]

Audio Clip Length

There is really only one useful property in the SoundEffect class: Duration. This property gives you the length of the audio clip in seconds. In the Draw() function of your sample program (Simple Audio Demo), you can print out the length of the audio clip.

[code]
string text = “Clip length: “ + clip.Duration.ToString();
spriteBatch.DrawString(font, text, Vector2.Zero, Color.White);
[/code]

When it comes down to playing audio clips in gameplay code, this class is not very helpful at all. What we need is a class with more functionality.

SoundEffectInstance

The SoundEffect class works, but not very well on its own. For one thing, a SoundEffect clip played does not work well in a complex audio environment (with music and different sound effects playing at the same time). For that, we need a helper class that can repeat playback with mixing support. That class is called SoundEffectInstance. This is really what we want to use when playing audio clips.

The SoundEffectInstance class enhances the basic functionality of SoundEffect with additional properties and methods that make it more useful in a real-world game. After loading the SoundEffect in LoadContent(), we can create an instance of the SoundEffectInstance class from its CreateInstance() method:

[code]
SoundEffect clip = Content.Load<SoundEffect>(“sound_clip”);
SoundEffectInstance clipInst = clip.CreateInstance();
[/code]

This class makes available several useful methods: Play(), Stop(), Pause(), and Resume(). And the Volume, Pitch, and Pan properties have been moved from parameters into real class properties, which we can modify outside of the Play() method. In addition, we can cause an audio clip to loop during playback with the IsLooping property.

MySoundEffect Class

I have prepared a helper class with essentially the sole purpose of just combining a SoundEffect and SoundEffectInstance object with a Load() method. We will use this helper class in the example coming up next. The source code for the class is found in Listing 18.1.

LISTING 18.1 Source Code for the MySoundEffect Class

[code]
public class MySoundEffect
{
private ContentManager p_content;
public SoundEffect effect;
public SoundEffectInstance instance;
public MySoundEffect(ContentManager content)
{
p_content = content;
effect = null;
instance = null;
}
public void Load(string assetName)
{
effect = p_content.Load<SoundEffect>(assetName);
instance = effect.CreateInstance();
}
}
[/code]

Creating the Audio Demo Program

The Audio Demo program is a complete example of audio for WP7 with some user input features as well, as shown in Figure 18.2. Five buttons are located on the screen that can be touched to play the five audio clips loaded into the program.

The Audio Demo program.
FIGURE 18.2 The Audio Demo program.

Button Class

The audio sample project uses a helper class called Button to draw numbered buttons on the screen that respond to screen touch input events. The Button class requires a bitmap file called button.png that is just a transparent image with a border around its edges. Listing 18.2 contains the source code for the Button class.

LISTING 18.2 The Button Class

[code]
public class Button : Sprite
{
public string text;
private SpriteBatch p_spriteBatch;
private SpriteFont p_font;
public Button(ContentManager content, SpriteBatch spriteBatch,
SpriteFont font) : base(content, spriteBatch)
{
p_spriteBatch = spriteBatch;
p_font = font;
Load(“button”);
text = ““;
color = Color.LightGreen;
}
public void Draw()
{
base.Draw();
Vector2 size = p_font.MeasureString(text);
Vector2 pos = position;
pos.X -= size.X / 2;
pos.Y -= size.Y / 2;
p_spriteBatch.DrawString(p_font, text, pos, color);
}
public bool Tapped(Vector2 pos)
{
Rectangle rect = new Rectangle((int)pos.X, (int)pos.Y, 1, 1);
return Boundary().Intersects(rect);
}
}
[/code]

Audio Demo Source

The main source code for the Audio Demo project is found in Listing 18.3. The required assets are a button image and five audio files named clip1, clip2, clip3, clip4, and clip5.

LISTING 18.3 Source Code for the Audio Demo Program

[code]
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
TouchLocation oldTouch;
SpriteFont font;
Button[] buttons;
MySoundEffect[] sounds;
int current = -1;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = “Content”;
TargetElapsedTime = TimeSpan.FromTicks(333333);
oldTouch = new TouchLocation();
}
protected override void Initialize()
{
base.Initialize();
this.IsMouseVisible = true;
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
font = Content.Load<SpriteFont>(“WascoSans”);
//create buttons
buttons = new Button[5];
for (int n = 0; n < 5; n++)
{
buttons[n] = new Button(Content, spriteBatch, font);
buttons[n].text = (n+1).ToString();
buttons[n].position = new Vector2(100 + 110 * n, 200);
}
//create sound clips
sounds = new MySoundEffect[5];
for (int n = 0; n < 5; n++)
{
sounds[n] = new MySoundEffect(Content);
sounds[n].Load(“Audio//clip” + (n+1).ToString());
}
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back ==
ButtonState.Pressed)
this.Exit();
TouchCollection touchInput = TouchPanel.GetState();
if (touchInput.Count > 0)
{
TouchLocation touch = touchInput[0];
if (touch.State == TouchLocationState.Pressed)
{
current = -1;
int n = 0;
foreach (Button b in buttons)
{
int x = (int)touch.Position.X;
int y = (int)touch.Position.Y;
if (b.Boundary().Contains(x,y))
{
current = n;
sounds[current].instance.Play();
break;
}
n++;
}
}
oldTouch = touch;
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin(SpriteSortMode.FrontToBack,
BlendState.AlphaBlend);
spriteBatch.DrawString(font, “Audio Demo”, Vector2.Zero,
Color.White);
foreach (Button b in buttons)
{
b.Draw();
}
if (current > -1)
{
string text = “Clip length: “ +
sounds[current].effect.Duration.ToString();
spriteBatch.DrawString(font, text, new Vector2(0, 400),
Color.White);
}
spriteBatch.End();
base.Draw(gameTime);
}
}
[/code]

We have now fully covered the XNA audio system with an example of how to load and play audio files. The helper class, MySoundEffect, can be dropped into any WP7 project and used to more easily handle the audio needs of a game.

Managing Lots of Sprites

Robot Trash Collectors

Our example in this hour is a simulation of robot trash collectors. The robots are represented as white circles, and the trash items as red squares. The robot cleaners will look for the closest trash item and move toward it, getting rid of the trash when it is touched. Figure 11.1 shows the simulation running with just one robot.

Simulation of robotic trash collectors with population control A.I.
FIGURE 11.1 Simulation of robotic trash collectors with population control A.I.

To make the simulation more interesting, it has the capability to automatically manage the amount of trash produced based on the number of cleaners present. A minus button at the bottom left removes cleaners, and its complementary plus button at the lower right adds new cleaners. As long as there is trash remaining, new trash is added rather slowly. But if the number of cleaners increases and the trash goes down, more trash is added more quickly to keep the cleaners busy. Figure 11.2 shows the simulation with five cleaners. Note the respawn time.

Five robot cleaners are present, which increases the trash rate.
FIGURE 11.2 Five robot cleaners are present, which increases the trash rate.

An algorithm of two trash items to one robot cleaner is used to adjust the speed. If there is fewer than twice the number of trash items compared to the cleaners, the speed is increased (by speeding up the respawn time). By watching the simulation run over time, you can see that a balance is maintained as long as the numbers are reasonable. Adding up to 100 or more robot cleaners causes the trash production to shift into high gear to keep up! See Figure 11.3 for an example.

The robot cleaner population is out of control!
FIGURE 11.3 The robot cleaner population is out of control!

Don’t let the primitive artwork dissuade you from studying the example in this hour. The code shared here will be extremely valuable in your own future game projects.

Building the Example

The simulation project this hour has a few asset requirements that you can source from the resource files for this hour, or just make yourself. The button image is just a 64×64 square. The robots are represented by a 32×32 white circle with alpha transparency around the edges. The trash is represented by a 32×32 red square. You are free to use different images if you want, perhaps even little robot and trash images! You can also change the theme of the art; how about insects and food?

Button Class

A helper class is needed to handle the buttons used to increase and decrease the number of robots. The Button class (see Listing 11.1) inherits from Sprite, so it will have all of Sprite’s capabilities and then some.

LISTING 11.1 Source Code for the Button Class

[code]
public class Button : Sprite
{
public string text;
private SpriteBatch p_spriteBatch;
private SpriteFont p_font;
public Button(ContentManager content, SpriteBatch spriteBatch,
SpriteFont font) :
base(content, spriteBatch)
{
p_spriteBatch = spriteBatch;
p_font = font;
Load(“button”);
text = ““;
color = Color.LightGreen;
}
public void Draw()
{
base.Draw();
Vector2 size = p_font.MeasureString(text);
Vector2 pos = position;
pos.X -= size.X / 2;
pos.Y -= size.Y / 2;
p_spriteBatch.DrawString(p_font, text, pos, color);
}
public bool Tapped(Vector2 pos)
{
Rectangle rect = new Rectangle((int)pos.X, (int)pos.Y, 1, 1);
return Boundary().Intersects(rect);
}
}
[/code]

As you can see from the code, a constructor requires ContentManager and SpriteBatch parameters (which are just passed directly to the Sprite constructor), as well as a third parameter, SpriteFont, so that the button can print text on its own. Draw() calculates the size of the text and tries to center it. The font being used in this example is Wasco Sans Bold 36-point, but you are welcome to use a different font if you want. The Tapped() method receives as a parameter the position of a click/tap and checks to see whether it (the button) was tapped, returning true or false.

Main Source Code

Listing 11.2 contains the main source code for the Entity Grouping Demo program. We’ll go over the new helper methods after this.

LISTING 11.2 Source Code for the Entity Grouping Demo Program

[code]
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
TouchLocation oldTouch;
Random rand;
SpriteFont font, buttonFont;
Button plus, minus;
List<Sprite> cleaners;
Texture2D circleImage;
List<Sprite> trash;
Texture2D trashImage;
int lastTime = 0;
int target = -1;
int respawn = 500;
int score = 0;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = “Content”;
TargetElapsedTime = TimeSpan.FromTicks(333333);
oldTouch = new TouchLocation();
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
rand = new Random();
spriteBatch = new SpriteBatch(GraphicsDevice);
font = Content.Load<SpriteFont>(“WascoSans”);
buttonFont = Content.Load<SpriteFont>(“ButtonFont”);
//create minus button
minus = new Button(Content, spriteBatch, buttonFont);
minus.position = new Vector2(32, 480-32);
minus.text = “-”;
//create plus button
plus = new Button(Content, spriteBatch, buttonFont);
plus.position = new Vector2(800 – 32, 480 – 32);
plus.text = “+”;
//create cleaners group
cleaners = new List<Sprite>();
circleImage = Content.Load<Texture2D>(“circle”);
AddCleaner();
//create trash group
trash = new List<Sprite>();
trashImage = Content.Load<Texture2D>(“trash”);
AddTrash();
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back ==
ButtonState.Pressed)
this.Exit();
//get state of touch input
TouchCollection touchInput = TouchPanel.GetState();
if (touchInput.Count > 0)
{
TouchLocation touch = touchInput[0];
if (touch.State == TouchLocationState.Pressed &&
oldTouch.State == TouchLocationState.Released)
{
if (minus.Tapped(touch.Position))
RemoveCleaner();
if (plus.Tapped(touch.Position))
AddCleaner();
}
oldTouch = touch;
}
//add new trash item periodically
if ((int)gameTime.TotalGameTime.TotalMilliseconds >
lastTime + respawn)
{
lastTime = (int)gameTime.TotalGameTime.TotalMilliseconds;
AddTrash();
}
if (trash.Count > cleaners.Count * 2)
{
respawn += 1;
if (respawn > 1000)
respawn = 1000;
}
else
{
respawn -= 1;
if (respawn < 10)
respawn = 10;
}
//move the cleaners
for (int n = 0; n < cleaners.Count; n++)
{
//find trash to pick up
target = FindNearestTrash(cleaners[n].position);
if (target > -1)
{
float angle = TargetAngle(cleaners[n].position,
trash[target].position);
cleaners[n].velocityLinear = Velocity(angle, 2.0f);
cleaners[n].Move();
}
//look for collision with trash
CollectTrash(cleaners[n].position);
//look for collision with other cleaners
for (int c = 0; c < cleaners.Count; c++)
{
if (n != c)
{
while (cleaners[n].Boundary().Intersects(
cleaners[c].Boundary()))
{
cleaners[c].velocityLinear.X += 0.001f;
cleaners[c].velocityLinear.Y += 0.001f;
cleaners[c].Move();
}
}
}
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.DarkBlue);
spriteBatch.Begin();
minus.Draw();
plus.Draw();
foreach (Sprite spr in trash)
spr.Draw();
foreach (Sprite spr in cleaners)
spr.Draw();
spriteBatch.DrawString(font,
“Cleaners:”+cleaners.Count.ToString(),
Vector2.Zero, Color.White);
spriteBatch.DrawString(font, “Trash:”+trash.Count.ToString(),
new Vector2(0,25), Color.White);
spriteBatch.DrawString(font, “Score:” + score.ToString(),
new Vector2(0, 50), Color.White);
spriteBatch.DrawString(font, “Respawn:” + respawn.ToString(),
new Vector2(0, 75), Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
[/code]

Main Simulation Functionality Code

The “meat and potatoes” code that drives the simulation is coming up next, in Listing 11.3. Here we find helper methods that look for the nearest trash items, move the robots toward the trash, add new robots, remove robots, and calculate distance and velocity. Some of these methods, like AddCleaner() and RemoveCleaner(), could have been just coded directly where they are called in the program, but this approach is much cleaner and reusable.

LISTING 11.3 Entity Grouping Demo Program (Continued)

[code]
void RemoveCleaner()
{
if (cleaners.Count > 0)
cleaners.RemoveAt(0);
}
void AddCleaner()
{
Sprite obj = new Sprite(Content, spriteBatch);
obj.image = circleImage;
obj.position = new Vector2((float)rand.Next(0, 760),
(float)rand.Next(0, 450));
cleaners.Add(obj);
}
void AddTrash()
{
Sprite obj = new Sprite(Content, spriteBatch);
obj.image = trashImage;
obj.position = new Vector2((float)rand.Next(0, 760),
(float)rand.Next(0, 450));
trash.Add(obj);
}
int FindNearestTrash(Vector2 pos)
{
int target = -1;
float closest = 9999;
if (trash.Count == 0) return -1;
for (int n = 0; n < trash.Count; n++)
{
float dist = Distance(pos, trash[n].position);
if (dist < closest)
{
closest = dist;
target = n;
}
}
return target;
}
void CollectTrash(Vector2 pos)
{
if (trash.Count == 0) return;
for (int n = 0; n < trash.Count; n++)
{
float dist = Distance(pos, trash[n].position);
if (dist < 8)
{
score++;
trash.RemoveAt(n);
break;
}
}
}
float Distance(Vector2 A, Vector2 B)
{
double diffX = A.X – B.X;
double diffY = A.Y – B.Y;
double dist = Math.Sqrt(Math.Pow(diffX, 2) + Math.Pow(diffY, 2));
return (float)dist;
}
float TargetAngle(Vector2 p1, Vector2 p2)
{
return TargetAngle(p1.X, p1.Y, p2.X, p2.Y);
}
float TargetAngle(double x1, double y1, double x2, double y2)
{
double deltaX = (x2 – x1);
double deltaY = (y2 – y1);
return (float)Math.Atan2(deltaY, deltaX);
}
Vector2 Velocity(float angle, float acceleration)
{
double x = Math.Cos(angle) * acceleration;
double y = Math.Sin(angle) * acceleration;
return new Vector2((float)x, (float)y);
}
}
[/code]

Simulating Group Dynamics

The key to this simulation example is a pair of linked lists called cleaners and trash. A linked list is a managed collection for a single type of data, like our Sprite class. In C#, the list is defined with the data type (Sprite) as a template in brackets:

[code]
List<Sprite> cleaners;
The list is created in LoadContent():
cleaners = new List<Sprite>();
[/code]

At this point, the list is ready to be filled with Sprite objects. Each object is a separate, complete Sprite object with its own properties and methods. A new object is added to the list with the Add() method. This code creates a new Sprite object and adds it to the list:

[code]
Sprite sprite = new Sprite(Content, spriteBatch);
sprite.position = new Vector2(0, 0);
cleaners.Add(sprite);
[/code]

Testing revealed that the simulation locks up when there are more than about 250 robots, at which point it is difficult to click the minus button to reduce the population.

You can add as many objects to the list as you want, using a for loop, or by reading data in from a level file, or by any other means, and the list will grow as needed to contain all the objects being added. When objects have been added to the list, they can be forgotten to a certain degree. It’s up to us to make sure we can identify each object inside the list later if we want to use a specific object. For instance, if all the objects for a game are stored in a list like this, and you want to highlight the player’s character, then there must be a way to uniquely identify that sprite among all the others. This can be done by adding an identifier to the Sprite class, such as an ID number or name string. We aren’t doing that in this simulation because every object has equal treatment.

Using List Objects

There will be at least two different points where all the objects in the list must be accessed—from Update() and Draw(). That is, again, the very least number of times, while you might need to access the list elsewhere to test for collisions or for other purposes. There are two ways to iterate the list, using a for loop or using a foreach iterator.

A property of List provides the number of items it contains, called Count. For example:

[code]
for (int n = 0; n < cleaners.Count; n++)
{
//reference cleaners[n]
}
[/code]

Another way to access a list is with a foreach loop such as this:

[code]
foreach (Sprite sprite in cleaners)
{
//reference sprite
}
[/code]

Creating and Using a List

A List is like an array, but it is much easier to use. Let’s learn how to create a List container for other objects.

  1. Define the new List variable in the program’s global variables section. In the brackets, you will define the type of data that the List will contain— which can be anything, such as Sprite or int or string.
    [code]
    List<string> groceries;
    [/code]
  2. Create or initialize the List variable, again with the data type in brackets. Plus, don’t forget the parentheses at the end! The parentheses mean this is a function—or rather, method—call, the constructor method to be precise.
    [code]
    groceries = new List<string>();
    [/code]
  3. Add items to the list like so:
    [code]
    groceries.Add(“butter”);
    groceries.Add(“milk”);
    groceries.Add(“bread”);
    [/code]
  4. Access the items in the list using either a for loop with the groceries.count property, or a foreach loop with the groceries object.
    [code]
    foreach (string item in groceries)
    {
    // … do something with the item here
    }
    [/code]

Iteration Techniques Compared

There are distinct advantages to both iteration mechanisms, depending on programming needs. The numeric for loop is helpful when you want to find the index position of a certain object in the list and then reference it later with indexers ([]). For instance, you might keep track of a “clicked” object with a number variable, and then just index inside the list with that variable, like so:

[code]
cleaners[clicked].Move();
[/code]

The foreach loop is easier to use if you just want to do a quick update of every object, and is commonly used to update the position or draw the object. Of course, there are many other purposes for a foreach iteration, and this is just one example. In the simulation project, all the robot cleaners are drawn with just two lines of code:

[code]
foreach (Sprite spr in cleaners)
spr.Draw();
[/code]

Very complex-appearing A.I. behaviors can seem to derive from surprisingly simple algorithms. When it comes down to analysis, simple rules determine human behavior in social environments too!

But in another part of the project, an index for loop is used to find the nearest trash. This snippet of code from the FindNearestTrash() method looks for the closest trash item by calculating the distance to every item in the trash list, keeping track of the index of the closest one with an int variable called closest. That specific trash item can then be found by indexing into trash with the variable.

[code]
for (int n = 0; n < trash.Count; n++)
{
float dist = Distance(pos, trash[n].position);
if (dist < closest)
{
closest = dist;
target = n;
}
}
[/code]

That’s all there is to it! In the final analysis, we use the distance calculation for many, many things in an ordinary video game!