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.

Sprite Color Animation

Getting Started with Color Animation

The first important point to consider when building an animation system that works with the Sprite class without infiltrating the Sprite class—that is, without mucking it up—is to design the animation system in such a way that transform or change values are used, not the internal properties of Sprite. Animation will be a passive, nonintrusive helper for Sprite, producing transform values that can be used or ignored, as the programmer sees fit. Animation can be integrated inside Sprite, or one or more animations can be applied to a sprite in the main program code instead.

The second significant aspect to this animation system is that animation applied to a sprite will not be permanent. A single animation is processed to a conclusion and then removed. What this allows us to do is write “fire and forget” animation code by setting up an animation event, turning it on, and then just watching it work. When completed, the animation object is deleted. Now, it’s perfectly fine if you want an animation to continue. You have control over when and where the animating property is set to false (which will cause it to be removed). To make this work in such a “fire and forget” manner, the Sprite class will need to be able to handle more than one animation at a time. This calls for a managed list.

The Main Animation Class

The primary or base Animation class, from which all “functional” animation subclasses will be derived, must have certain methods in place for modifying properties within Sprite. If we want to animate the color, a ModifyColor() method must be included. If we want to animate the scale, a ModifyScale() method is required. There really aren’t very many such methods needed in the base Animation class, because we need to animate only things that will affect a sprite’s appearance or behavior. Remember, our Sprite class already has the capability to perform transforms (changing the position, rotation, and scaling). Although it is possible to animate the basic transform properties in Sprite, that will be rare. Nevertheless, we still must give the programmer the ability to animate the transforms. Listing 12.1 contains our base Animation class.

LISTING 12.1 Animation Class Source Code

[code]
public class Animation
{
public bool animating;
public Animation()
{
animating = false;
}
public virtual void Update()
{
}
public virtual Color ModifyColor(Color original)
{
return original;
}
public virtual Vector2 ModifyPosition(Vector2 original)
{
return original;
}
public virtual float ModifyRotation(float original)
{
return original;
}
public virtual float ModifyScale(float original)
{
return original;
}
}
[/code]

Using Animation as a Base Class

Note how the methods in Animation return the passed parameter. This is a default behavior that will just perpetuate any properties that are not modified by a subclass. For instance, if we are doing just color animation, and not changing rotation or any other property, then rotation is completely ignored by the subclass and will have no effect on the animation being processed.

A subclass of Animation should override at least one of the ModifyXXX() methods in order to do something useful. Unless at least one of them is modified, no animation will occur and the class will essentially do nothing. On the flip side, more than one type of animation can be performed by the same class! Suppose you want a sprite to move back and forth on the screen while rotating and scaling—this animation system can handle that task. The sprite can then be used for collision testing, and all other aspects of sprite behavior remain intact! Perhaps the simplest functional subclass of Animation might look like this:

[code]

public class AnimationTemplate : Animation
{
public AnimationTemplate()
: base()
{
}
public void Update()
{
}
}
[/code]

You can use this as a template for your own custom animations. Just override any of the ModifyXXX() methods (such as ModifyColor()) to modify the properties you want to affect a sprite’s behavior. The Update() method can be used for generalpurpose processing. In the next two hours, we will use Update() as a general-purpose “pump” or “motor” for frame animation and transforms. Note that you can also add any variables you need to your Animation subclass. You can also override the parameter list of the modification methods to produce custom results (such as custom subsets of an existing animation).

Modifications to the Sprite Class

The Sprite class will need a few changes to support animation. First, there’s the addition of the Animation variable as a private:

[code]
private Animation p_animation;
[/code]

Next, there’s initialization of the variable in the Sprite constructor:

[code]
p_animation = null;
[/code]

And next, we need a method to set the current animation. We will eventually replace this with a List and support more than one animation at a time, but for now we’ll start with first things first!

[code]
public void SetAnimation(Animation animation)
{
p_animation = animation;
}
[/code]

Finally, we need a new method to get animation up and running! The following Animate() method will evolve quite a bit over the next two chapters. At this point, we need to work with only one type of animation (color cycling).

[code]
public void Animate()
{
if (p_animation != null)
{
if (p_animation.animating)
{
this.color = p_animation.ModifyColor(this.color);
}
}
}
[/code]

Color Animation

Color animation begins with a solid color that can then be transformed by manipulating the color components (red, green, blue, and alpha). We’ll see how to write a basic solid-color class to begin experimenting with color animation before getting into color cycling.

Solid Colors

A solid-color “animation” might seem contradictory, but there actually is a very good use for such a thing. Although it is true that a sprite can be drawn in any desired color, that often requires additional global variables because the Sprite class does not keep track of color changes, just the color property. To change the color on the fly while a game is running would require globals to keep track of the colors and a conditional variable used to trigger the color change. We can do this more easily with a subclass of Animation that works with solid colors.

Let’s begin with Listing 12.2, the source code to the new SolidColor class, which inherits from Animation. There’s very little to this class, which makes it a good starting point for our study of color animation coming up.

LISTING 12.2 Source Code for the SolidColor Class

[code]
public class SolidColor : Animation
{
public Color color;
public SolidColor(Color color)
: base()
{
this.color = color;
animating = true;
}
public override Color ModifyColor(Color original)
{
return color;
}
}
[/code]

The Solid Color project is part of the Color Animation Demo solution included with this hour (several projects in the solution share a common content project for convenience). To run this specific project in the solution, right-click the project name and select Debug, Start New Instance. In this manner, any project in a larger solution can be debugged, while F5 will try to run the currently “active” project. Figure 12.1 shows the program running. There are three boxes that move on the screen, and they change color anytime they hit the edge. Simple as that! The source code to the project is found in Listing 12.3.

Solid color transform as a form of “animation.”
FIGURE 12.1 Solid color transform as a form of “animation.”

LISTING 12.3 Source Code for the Solid Color Project

[code]
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Random rand;
SpriteFont font;
Texture2D shapeImage;
List<Sprite> shapes;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = “Content”;
TargetElapsedTime = TimeSpan.FromTicks(333333);
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
rand = new Random();
spriteBatch = new SpriteBatch(GraphicsDevice);
font = Content.Load<SpriteFont>(“WascoSans”);
shapeImage = Content.Load<Texture2D>(“box”);
Sprite box1 = new Sprite(Content, spriteBatch);
box1.image = shapeImage;
box1.position = new Vector2(rand.Next(0, 200), rand.Next(0, 380));
box1.velocityLinear = new Vector2(4.0f, 3.0f);
box1.origin = new Vector2(64, 64);
box1.SetAnimation(null);
Sprite box2 = new Sprite(Content, spriteBatch);
box2.image = shapeImage;
box2.position = new Vector2(rand.Next(200, 400), rand.Next(0, 380));
box2.velocityLinear = new Vector2(4.0f, 3.0f);
box2.origin = new Vector2(64, 64);
box2.SetAnimation(null);
Sprite box3 = new Sprite(Content, spriteBatch);
box3.image = shapeImage;
box3.position = new Vector2(rand.Next(400, 600), rand.Next(0, 380));
box3.velocityLinear = new Vector2(4.0f, 3.0f);
box3.origin = new Vector2(64, 64);
box3.SetAnimation(null);
shapes = new List<Sprite>();
shapes.Add(box1);
shapes.Add(box2);
shapes.Add(box3);
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back ==
ButtonState.Pressed)
this.Exit();
foreach (Sprite spr in shapes)
{
spr.Move();
if (spr.position.X < 0 || spr.position.X > 800 ||
spr.position.Y < 0 || spr.position.Y > 480)
{
spr.SetAnimation(new SolidColor(
new Color(rand.Next(255), rand.Next(255),
rand.Next(255))));
if (spr.position.X < -64 || spr.position.X > 800+64)
spr.velocityLinear.X *= -1;
if (spr.position.Y < -64 || spr.position.Y > 480+64)
spr.velocityLinear.Y *= -1;
}
else
spr.SetAnimation(new SolidColor(Color.White));
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin();
foreach (Sprite spr in shapes)
{
spr.Animate();
spr.Draw();
}
spriteBatch.DrawString(font, “Solid Color Demo”,
new Vector2(0, 0), Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
[/code]

Color Cycling

One common color animation involves cycling a color within a range and either going back and forth between two limits or wrapping around in either direction. A base CycleColor class will help us get started and then we can write subclasses from it to do specific color movements. The source code is found in Listing 12.4.

LISTING 12.4 Source Code for the CycleColor Class

[code]
public class CycleColor : Animation
{
public int red, green, blue, alpha;
public CycleColor(int red, int green, int blue, int alpha)
: base()
{
this.red = red;
this.green = green;
this.blue = blue;
this.alpha = alpha;
animating = true;
}
public override Color ModifyColor(Color original)
{
Color modified = original;
if (animating)
{
int R = original.R + red;
int G = original.G + green;
int B = original.B + blue;
int A = original.A + alpha;
if (R < 0 || R > 255 || G < 0 || G > 255 || B < 0 || B > 255
|| A < 0 || A > 255)
{
animating = false;
}
modified = new Color(R, G, B, A);
}
return modified;
}
}
[/code]

This class will cycle a color from its original values upward or downward based on the color cycling modifiers passed to the CycleColor() constructor until the range is exceeded, at which point animation stops. The modifiers will usually be +1 or -1 for each color component, unless faster color cycling is desired. Let’s test it with a quick sample program called Cycle Color Animation (see Listing 12.5).

Three boxes are added: colored red, green, and blue. The boxes fade completely to black based on the CycleColor class’s properties, but if different colors were used for each one, they would not fade completely to black, but would just modify the color components to produce different color results. Setting the initial conditions (such as original color) does have an effect and should be considered ahead of time. In the combined Visual Studio solution for this hour, this project is called Cycle Color Animation, and is shown in Figure 12.2.

Demonstrating color cycling with three rotating boxes of different colors.
FIGURE 12.2 Demonstrating color cycling with three rotating boxes of different colors.

LISTING 12.5 Source Code to the Cycle Color Animation Project

[code]
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
TouchLocation oldTouch;
SpriteFont font;
Texture2D shapeImage;
List<Sprite> shapes;
CycleColor cycleRed, cycleGreen, cycleBlue;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = “Content”;
TargetElapsedTime = TimeSpan.FromTicks(333333);
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
font = Content.Load<SpriteFont>(“WascoSans”);
shapeImage = Content.Load<Texture2D>(“box”);
Sprite redBox = new Sprite(Content, spriteBatch);
redBox.image = shapeImage;
redBox.position = new Vector2(200, 240);
redBox.origin = new Vector2(64, 64);
redBox.velocityAngular = 0.05f;
redBox.color = new Color(255, 0, 0);
Sprite greenBox = new Sprite(Content, spriteBatch);
greenBox.image = shapeImage;
greenBox.position = new Vector2(400, 240);
greenBox.origin = new Vector2(64, 64);
greenBox.velocityAngular = 0.05f;
greenBox.color = new Color(0, 255, 0);
Sprite blueBox = new Sprite(Content, spriteBatch);
blueBox.image = shapeImage;
blueBox.position = new Vector2(600, 240);
blueBox.origin = new Vector2(64, 64);
blueBox.velocityAngular = 0.05f;
blueBox.color = new Color(0, 0, 255);
cycleRed = new CycleColor(-1, 0, 0, 0);
redBox.SetAnimation(cycleRed);
cycleGreen = new CycleColor(0, -1, 0, 0);
greenBox.SetAnimation(cycleGreen);
cycleBlue = new CycleColor(0, 0, -1, 0);
blueBox.SetAnimation(cycleBlue);
shapes = new List<Sprite>();
shapes.Add(redBox);
shapes.Add(greenBox);
shapes.Add(blueBox);
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back ==
ButtonState.Pressed)
this.Exit();
foreach (Sprite spr in shapes)
{
spr.Rotate();
spr.Move();
}
if (!cycleBlue.animating)
{
cycleBlue.blue *= -1;
cycleBlue.animating = true;
}
if (!cycleGreen.animating)
{
cycleGreen.green *= -1;
cycleGreen.animating = true;
}
if (!cycleRed.animating)
{
cycleRed.red *= -1;
cycleRed.animating = true;
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin();
foreach (Sprite spr in shapes)
{
spr.Animate();
spr.Draw();
}
spriteBatch.DrawString(font, “Color Animation Demo”,
new Vector2(0, 0), Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
[/code]

The examples in this hour are combined into a single Visual Studio solution so that they can all share the same content (a single white box image). To run a specific project in a combined solution, right-click the project and use Debug, Start New Instance. Optionally, you can highlight any one of the projects, set it as the Active Project, and then press F5 to run it.

Color Bouncing

The code in the previous example can be improved upon with a new subclass of CycleColor that automatically “bounces” the color components within a specified range. The new subclass is called CycleColorBounce, as found in Listing 12.6. Since this class does not assume that the color component range will bounce between 0 and 255, there is a min and max property for each color component, defined as integers. Although a more complex data type like Vector4 would clean up the code a bit, I was going for clarity. Now, this Animation subclass does not ever end by setting animating to false, so this animation will continue forever unless an intervention takes place. Another possibility is to have it perform a single bounce forward and backward before ending. Then, if you want to perform the animation again, it can be restarted.

LISTING 12.6 Source Code to the CycleColorBounce Class

[code]
public class CycleColorBounce : CycleColor
{
public int rmin, rmax, gmin, gmax, bmin, bmax, amin, amax;
public CycleColorBounce(int red, int green, int blue, int alpha)
: base(red,green,blue,alpha)
{
rmin = gmin = bmin = amin = 0;
rmax = gmax = bmax = amax = 255;
}
public override Color ModifyColor(Color original)
{
Color modified = original;
if (animating)
{
int R = original.R + red;
int G = original.G + green;
int B = original.B + blue;
int A = original.A + alpha;
if (R < rmin)
{
R = rmin;
red *= -1;
}
else if (R > rmax)
{
R = rmax;
red *= -1;
}
if (G < gmin)
{
G = gmin;
green *= -1;
}
else if (G > gmax)
{
G = gmax;
green *= -1;
}
if (B < bmin)
{
B = bmin;
blue *= -1;
}
else if (B > bmax)
{
B = bmax;
blue *= -1;
}
if (A < amin)
{
A = amin;
alpha *= -1;
}
else if (A > amax)
{
A = amax;
alpha *= -1;
}
modified = new Color(R, G, B, A);
}
return modified;
}
}
[/code]

The example for color bouncing is very similar to the previous example, with only minor changes to the variable declarations and initialization of the objects. I opted to turn off rotation of the sprites just to make this example stand apart from the previous one a bit. The source code to the Color Bouncing program that demonstrates this class is found in Listing 12.7.

LISTING 12.7 Source Code to the Color Bouncing Program

[code]
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteFont font;
Texture2D shapeImage;
List<Sprite> shapes;
CycleColorBounce cycleRed, cycleGreen, cycleBlue;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = “Content”;
TargetElapsedTime = TimeSpan.FromTicks(333333);
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
font = Content.Load<SpriteFont>(“WascoSans”);
shapeImage = Content.Load<Texture2D>(“box”);
Sprite redBox = new Sprite(Content, spriteBatch);
redBox.image = shapeImage;
redBox.position = new Vector2(200, 240);
redBox.origin = new Vector2(64, 64);
redBox.color = new Color(255, 0, 0);
Sprite greenBox = new Sprite(Content, spriteBatch);
greenBox.image = shapeImage;
greenBox.position = new Vector2(400, 240);
greenBox.origin = new Vector2(64, 64);
greenBox.color = new Color(0, 255, 0);
Sprite blueBox = new Sprite(Content, spriteBatch);
blueBox.image = shapeImage;
blueBox.position = new Vector2(600, 240);
blueBox.origin = new Vector2(64, 64);
blueBox.color = new Color(0, 0, 255);
cycleRed = new CycleColorBounce(-5, 0, 0, 0);
cycleRed.rmin = 100;
cycleRed.rmax = 200;
redBox.SetAnimation(cycleRed);
cycleGreen = new CycleColorBounce(0, -10, 0, 0);
cycleGreen.gmin = 150;
cycleGreen.gmax = 255;
greenBox.SetAnimation(cycleGreen);
cycleBlue = new CycleColorBounce(0, 0, -20, 0);
cycleBlue.bmin = 0;
cycleBlue.bmax = 255;
blueBox.SetAnimation(cycleBlue);
shapes = new List<Sprite>();
shapes.Add(redBox);
shapes.Add(greenBox);
shapes.Add(blueBox);
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back ==
ButtonState.Pressed)
this.Exit();
foreach (Sprite spr in shapes)
{
spr.Rotate();
spr.Move();
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin();
foreach (Sprite spr in shapes)
{
spr.Animate();
spr.Draw();
}
spriteBatch.DrawString(font, “Color Bouncing Demo”,
new Vector2(0, 0), Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
[/code]

This example is included in the Color Animation Demo solution, called Color Bouncing, and is shown in Figure 12.3. Each of the three boxes performs color cycle bouncing at a different rate to demonstrate the versatility of the animation system.

All the color animation being demonstrated in this hour can be applied to sprites with actual game artwork rather than a white shape. These special effects are demonstrated on a simple white box only for illustration, to show what is possible!

Animating color components bouncing between minimum and maximum values.
FIGURE 12.3 Animating color components bouncing between minimum and maximum values.

Getting Started with Visual C# 2010 for Windows Phone

Visual C# 2010 Express

At the time of this writing, the current version of the development tool for Windows Phone 7 is Visual Studio 2010. To make development simple for newcomers to the Windows Mobile platform, Microsoft has set up a package that will install everything you need to develop, compile, and run code in the emulator or on a physical Windows Phone device—for free. The download URL at this time is http://www.microsoft. com/express/Phone. If you are using a licensed copy of Visual Studio 2010, such as the Professional, Premium, or Ultimate edition, then you will find XNA Game Studio 4.0 and related tools at http://create.msdn.com (the App Hub website). The App Hub website, shown in Figure 2.1, also contains links to the development tools.

The App Hub website has download links to the development tools.
FIGURE 2.1 The App Hub website has download links to the development tools.

The most common Windows Phone developer will be using the free version of Visual C# 2010, called the Express edition. This continues the wonderful gift Microsoft first began giving developers with the release of Visual Studio 2005. At that time, the usual “professional” versions of Visual Studio were still available, of course, and I would be remiss if I failed to point out that a licensed copy of Visual Studio is required by any person or organization building software for business activities (including both for-profit and nonprofit). The usual freelance developer will also need one of the professional editions of Visual Studio, if it is used for profit. But any single person who is just learning, or any organization that just wants to evaluate Visual Studio for a short time, prior to buying a full license, can take advantage of the free Express editions. I speak of “editions” because each language is treated as a separate product. The professional editions include all the languages, but the free Express editions, listed here, are each installed separately:

  • Visual C# 2010 Express
  • Visual Basic 2010 Express
  • Visual C++ 2010 Express

The version of Visual Studio we will be using is called Visual Studio 2010 Express for Windows Phone. This is a “package” with the Windows Phone SDK already prepackaged with Visual C# 2010 Express. (Despite the name, “Visual Studio” here supports only the C# language.) It’s a nice package that makes it very easy to get started doing Windows Phone development. But if you are using Visual Studio 2010 Professional (or one of the other editions) along with the Windows Phone SDK, you will see a lot more project templates in the New Project dialog, shown in Figure 2.2.

The New Project dialog in Visual C# 2010 Express.
FIGURE 2.2 The New Project dialog in Visual C# 2010 Express.
  • Windows Phone Application (Visual C#)
  • Windows Phone Databound Application (Visual C#)
  • Windows Phone Class Library (Visual C#)
  • Windows Phone Panorama Application (Visual C#)
  • Windows Phone Pivot Application (Visual C#)
  • Windows Phone Game (4.0) (Visual C#)
  • Windows Phone Game Library (4.0) (Visual C#)
  • Windows Game (4.0) (Visual C#)
  • Windows Game Library (4.0) (Visual C#)
  • Xbox 360 Game (4.0) (Visual C#)
  • Xbox 360 Game Library (4.0) (Visual C#)
  • Content Pipeline Extension Library (4.0)
  • Empty Content Project (4.0) (Visual C#)

As you can see, even in this limited version of Visual Studio 2010, all the XNA Game Studio 4.0 project templates are included—not just those limited to Windows Phone. The project templates with “(4.0)” in the name come from the XNA Game Studio SDK, which is what we will be primarily using to build Windows Phone games. The first five project templates come with the Silverlight SDK. That’s all we get with this version of Visual Studio 2010. It’s not even possible to build a basic Windows application here—only Windows Phone (games or apps), Windows (game only), and Xbox 360 (obviously, game only). The first five project templates are covered in the next section, “Using Silverlight for WP7.”

Did you notice that all of these project templates are based on the C# language? Unfortunately for Visual Basic fans, we cannot use Basic to program games or apps for Windows Phone using Visual C# 2010 Express. You can install Visual Basic 2010 Express with Silverlight and then use that to make WP7 applications. XNA, however, supports only C#.

We don’t look at Xbox 360 development in this book at all. If you’re interested in the subject, see my complementary book XNA Game Studio 4.0 for Xbox 360 Developers [Cengage, 2011].

Using Silverlight for WP7

Microsoft Silverlight is a web browser plug-in “runtime.” Silverlight is not, strictly speaking, a development tool. It might be compared to DirectX, in that it is like a library, but for rich-content web apps. It’s similar to ASP.NET in that Silverlight applications run in a web browser, but it is more capable for building consumer applications (while ASP.NET is primarily for business apps). But the way Silverlight applications are built is quite different from ASP.NET—it’s more of a design tool with an editing environment called Expression Blend. The design goal of Silverlight is to produce web applications that are rich in media support, and it supports all standard web browsers (not just Internet Explorer, which is a pleasant surprise!), including Firefox and Safari on Mac.

Using Expression Blend to Build Silverlight Projects

Microsoft Expression Blend 4 is a free tool installed with the Windows Phone package that makes it easier to design Silverlight-powered web pages with rich media content support. Blend can be used to design and create engaging user experiences for Silverlight pages. Windows application support is possible with the WPF (Windows Presentation Foundation) library. A key feature of Blend is that it separates design from programming. As you can see in Figure 2.3, the New Project dialog in Blend lists the same project types found in Visual C# 2010 Express.

Expression Blend is a Silverlight development tool for web designers.
FIGURE 2.3 Expression Blend is a Silverlight development tool for web designers.

Let’s create a quick Expression Blend project to see how it works. While working on this quick first project, keep in mind that we’re not building a “Blend” project, but a “Silverlight” project—using Blend. Blend is a whole new Silverlight design and development tool, not affiliated with Visual Studio (but probably based on it). The Silverlight library is already installed on the Windows Phone emulator and actual phones.

Here’s how to create the project:

  1. Create a Windows Phone Application project using the New Project dialog. Click File, New Project.
  2. Blend creates a standard project for Windows Phone, complete with an application title and opening page for the app.
  3. Run the project with Project, Run Project, or by pressing F5. The running program is shown in Figure 2.4.
Our first project with Expression Blend.
FIGURE 2.4 Our first project with Expression Blend.

This is a useless app, but it shows the steps needed to create a new project and run it in the Windows Phone emulator. Did you notice how large the emulator window appears? That’s full size with respect to the screen resolution of WP7. As you’ll recall from the first hour, the resolution is 480×800. That is enough pixels to support 480p DVD movies, but not the 740p or 1080p HD standards. Still, DVD quality is great for a phone! And when rotated to landscape mode, 800×480 is a lot of screen real estate for a game too.

You can make quick and easy changes to the labels at the top and experiment with the design controls in the toolbox on the left. Here you can see that the application title and page title have been renamed, and some images and shapes have been added to the page. Pressing F5 again brings it up in the emulator, shown in Figure 2.5.

Now that you’ve seen what’s possible with Expression Blend’s more designer-friendly editor, let’s take a look at the same Silverlight project in Visual Studio 2010.

Silverlight Projects

The Silverlight runtime for WP7 supports some impressive media types with many different audio and video codecs, vector graphics, bitmap graphics, and animation. That should trigger the perimeter alert of any game developer worth their salt! Silverlight brings some highly interactive input mechanisms to the Web, including accelerometer motion detection, multitouch input (for devices that support it),camera, microphone input, and various phone-type features (like accessing an address book and dialing).

Making quick changes to the page is easy with Expression Blend.
FIGURE 2.5 Making quick changes to the page is easy with Expression Blend.

To find out whether your preferred web browser supports Silverlight, visit the installer web page at http://www.microsoft.com/getsilverlight/get-started/install.

The Visual Studio 2010 project templates specific to Silverlight are highlighted in bold in the list below. These are the same project templates shown in Expression Blend!

  • Windows Phone Application (Visual C#)
  • Windows Phone Databound Application (Visual C#)
  • Windows Phone Class Library (Visual C#)
  • Windows Phone Panorama Application (Visual C#)
  • Windows Phone Pivot Application (Visual C#)
  • Windows Phone Game (4.0) (Visual C#)
  • Windows Phone Game Library (4.0) (Visual C#)
  • Windows Game (4.0) (Visual C#)
  • Windows Game Library (4.0) (Visual C#)
  • Xbox 360 Game (4.0) (Visual C#)
  • Xbox 360 Game Library (4.0) (Visual C#)
  • Content Pipeline Extension Library (4.0)
  • Empty Content Project (4.0) (Visual C#)

Let’s create a quick project in Visual Studio in order to compare it with Expression Blend. You’ll note right away that it is not the same rich design environment, but is more programmer oriented.

Comparing Visual Studio with Expression Blend

Let’s create a new project in Visual C# 2010 in order to compare it with Expression Blend. Follow these steps:

  1. Open the New Project dialog with File, New Project.
  2. Next, in the New Project dialog, choose the target folder for the project and type in a project name, as shown in Figure 2.6.

    Creating a new Silverlight project in Visual C# 2010 Express.
    FIGURE 2.6 Creating a new Silverlight project in Visual C# 2010 Express.
  3. Click the OK button to generate the new project shown in the figure. Not very user-friendly, is it? First of all, double-clicking a label does not make it editable, among other limitations (compared to Expression Blend). Where are the control properties? Oh, yes, in the Properties window in Visual Studio. See Figure 2.7. This is also very data-centric, which programmers love and designers loathe. The view on the left is how the page appears on the device (or emulator); the view on the right is the HTML-like source code behind the page, which can be edited.
  4. Bring up the Properties window (if not already visible) by using the View menu. Select a control on the page, such as the application title. Scroll down in the Properties to the Text property, where you can change the label’s text, as shown in Figure 2.8. Play around with the various properties to change the horizontal alignment, the color of the text, and so on. Open the Toolbox (located on the left side of Visual Studio) to gain access to new controls such as the Ellipse control shown here.
    The new Silverlight project has been created.
    FIGURE 2.7 The new Silverlight project has been created.

    Adding content to the Silverlight page.
    FIGURE 2.8 Adding content to the Silverlight page.

XNA Game Studio

XNA Game Studio 4.0 was released in the fall of 2010. (From now on, let’s just shorten this to “XNA” or “XNA 4.0”, even though “Game Studio” is the name of the SDK, and “XNA” is the overall product name.) XNA 4.0 saw several new improvements to the graphics system, but due to the hardware of the Xbox 360, XNA is still based on Direct3D 9 (not the newer versions, Direct3D 10 or 11). This is actually very good news for a beginner, since Direct3D 9 is much easier to learn than 10 or 11. Although XNA abstracts the C++-based DirectX libraries into the C#-based XNA Framework, there is still much DirectX-ish code that you have to know in order to build a capable graphics engine in XNA. While XNA 4.0 added WP7 support, it simultaneously dropped support for Zune (the portable multimedia and music player).

I have a Zune HD, and it’s a nice device! It can play 720p HD movies and even export them to an HDTV via an adapter and HDMI cable. It plays music well too. But, like many consumers, I just did not have much incentive to go online and download games for the Zune. This is, of course, purely a subjective matter of opinion, but it’s disappointing for game developers who put effort into making games for Zune. Fortunately, the code base is largely the same (thanks to XNA and C#), so those Zune games can be easily ported to WP7 now.

Rendering states, enumerations, return values, and so forth are the same in XNA as they are in Direct3D, so it could be helpful to study a Direct3D book to improve your skills as an XNA programmer!

The project templates for Windows Phone might surprise you—there are only two! We can build a Windows Phone game or a game library. All the other templates are related to the other platforms supported by XNA.

  • Windows Phone Application (Visual C#)
  • Windows Phone Databound Application (Visual C#)
  • Windows Phone Class Library (Visual C#)
  • Windows Phone Panorama Application (Visual C#)
  • Windows Phone Pivot Application (Visual C#)
  • Windows Phone Game (4.0) (Visual C#)
  • Windows Phone Game Library (4.0) (Visual C#)
  • Windows Game (4.0) (Visual C#)
  • Windows Game Library (4.0) (Visual C#)
  • Xbox 360 Game (4.0) (Visual C#)
  • Xbox 360 Game Library (4.0) (Visual C#)
  • Content Pipeline Extension Library (4.0)
  • Empty Content Project (4.0) (Visual C#)

Let’s build a quick XNA project for Windows Phone to see what it looks like. We’ll definitely be doing a lot of this in upcoming chapters since XNA is our primary focus (the coverage of Silverlight was only for the curious—grab a full-blown Silverlight or Expression Blend book for more complete and in-depth coverage.

Creating Your First XNA 4.0 Project

Let’s create a new XNA 4.0 project in Visual C# 2010, so we can use this as a comparison with the previous project created with Expression Blend. Follow these steps:

  1. Create a new project. We’ll be basing these tutorials around Visual Studio 2010 Express for Windows Phone. The processes will be similar to using the Professional version, but you will see many more project templates in the New Project dialog. Open the File menu and choose New Project. The New Project dialog is shown in Figure 2.9.

    Creating a new XNA 4.0 project.
    FIGURE 2.9 Creating a new XNA 4.0 project.
  2. The new project has been created. Note, from Figure 2.10, the code that has been automatically generated for the XNA project. If you have ever worked with XNA before, this will be no surprise—the code looks exactly like the generated code for Windows and Xbox 360 projects!

    The new XNA 4.0 project has been created.
    FIGURE 2.10 The new XNA 4.0 project has been created.
  3. Run the project with Build, Run, or by pressing F5. The emulator will come up, as shown in Figure 2.11. Doesn’t look like much—just a blue screen! That’s exactly what we want to see, because we haven’t written any game code yet.
  4. Add a SpriteFont to the Content project. Right-click the content project, called XNA ExampleContent(Content) in the Solution Explorer. Choose Add, New Item, as shown in Figure 2.12.
    Running the XNA project in the Windows Phone emulator.
    FIGURE 2.11 Running the XNA project in the Windows Phone emulator.

    Adding a new item to the content project.
    FIGURE 2.12 Adding a new item to the content project.
  5. In the Add Item dialog, choose the Sprite Font item from the list, as shown in Figure 2.13, and leave the filename as SpriteFont1.spritefont.

    Adding a new SpriteFont content item to the project.
    FIGURE 2.13 Adding a new SpriteFont content item to the project.
  6. Create the font variable. The comments in the code listing have been removed to make the code easier to read. We’ll dig into the purpose of all this code in the next hour, so don’t be concerned with understanding all the code yet. Type in the two new bold lines of code shown here to add the font variable.
    [code]
    public class Game1 : Microsoft.Xna.Framework.Game
    {
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    //new font variable
    SpriteFont font;
    public Game1()
    {
    graphics = new GraphicsDeviceManager(this);
    Content.RootDirectory = “Content”;
    TargetElapsedTime = TimeSpan.FromTicks(333333);
    }
    [/code]
  7. Load the font. Enter the two new lines shown in bold in the LoadContent method.
    [code]
    protected override void Initialize()
    {
    base.Initialize();
    }
    protected override void LoadContent()
    {
    spriteBatch = new SpriteBatch(GraphicsDevice);
    //load the font
    font = Content.Load<SpriteFont>(“SpriteFont1”);
    }
    protected override void UnloadContent()
    {
    }
    [/code]
  8. Print a message on the screen. Using the SpriteBatch and SpriteFont objects, we can print any text message. This is done from the Draw method—add the code highlighted in bold.
    [code]
    protected override void Update(GameTime gameTime)
    {
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back ==
    ButtonState.Pressed)
    this.Exit();
    base.Update(gameTime);
    }
    protected override void Draw(GameTime gameTime)
    {
    GraphicsDevice.Clear(Color.CornflowerBlue);
    //print a message
    spriteBatch.Begin();
    string text = “HELLO FROM XNA!”;
    Vector2 pos = font.MeasureString(text);
    spriteBatch.DrawString(font, text, pos, Color.White);
    spriteBatch.End();
    base.Draw(gameTime);
    }
    }
    [/code]
  9. Run the program using Debug, Start Debugging, or by pressing F5. The program will come up in the emulator, shown in Figure 2.14. Now there’s just one big problem: The font is too small, and the screen needs to be rotated to landscape mode so we can read it!
  10. Click the emulator window to cause the little control menu to appear at the upper right. There are two icons that will rotate the window left or right, allowing us to switch from portrait to landscape mode. All XNA projects will default to portrait mode by default. Landscape mode is shown in Figure 2.15.
    The text message is displayed in the emulator— sideways!
    FIGURE 2.14 The text message is displayed in the emulator— sideways!

    Rotating the emulator window to landscape mode for XNA projects.
    FIGURE 2.15 Rotating the emulator window to landscape mode for XNA projects.
  11. Enlarge the font. We’re almost done; there’s just one final thing I want to show you how to do here. Open the font file you created, SpriteFont1. spritefont. Change the size value from 14 to 36. Now rerun the project by pressing F5. The new, large font is shown in Figure 2.16.

    Enlarging the font to make it more readable.
    FIGURE 2.16 Enlarging the font to make it more readable.

XNA or Silverlight: What’s the Verdict?

We have now seen two projects developed with the two different, and somewhat competing tools: XNA and Silverlight. Which should we choose? This is really a matter of preference when it comes to developing a game. Although XNA is far more capable due to its rendering capabilities, Silverlight can be used to make a game as well, with form-based control programming. For portable, touchscreen applications, it’s a given: Silverlight. But for serious game development, XNA is the only serious option.

We covered quite a bit of information regarding Visual Studio 2010, the project templates available for Windows Phone, and the value-added tool Expression Blend. A sample project was presented using Expression Blend with a corresponding Silverlight project in Visual Studio, as well as an XNA project. We’re off to a good start and already writing quite a bit of code! In the next hour, you will create your first Windows Phone game.

Making Games for Windows Phone 7

Getting Started with Windows Phone 7

There are two ways we can develop games for Windows Phone 7: Silverlight and XNA Game Studio. Although Silverlight does have basic graphics capabilities, those capabilities are provided to support applications and are not ideally suited for games. XNA, on the other hand, was developed specifically for game development!

Before learning all about XNA Game Studio 4.0, Visual C# 2010, projects, configurations, Xbox Live, App Hub, and other great things that will interest a game developer, we need to first understand this new platform. Windows Phone 7, which we might call WP7 for short, is an operating system for smartphone devices.

In “the old days,” if you knew how to turn on a computer, you were called a “computer geek.” It didn’t really matter if you knew how to do anything with a computer; it was just assumed by many (especially in the older generations) that turning it on required knowledge of the black arts in electronics wizardry. That seems to be the case with most new technology, which people will tend to resist and perhaps even fear to a certain degree. When cars were first invented at the dawn of the automobile industry, people who drove around in a “horseless carriage” were considered snobbish, among the wealthy class—that is, until Henry Ford built a car that just about anyone could afford to buy. Not only did most people not have a computer in the early days, but most people at the time did not even begin to know how to go about buying one.

I’m speaking in terms of the time period around the mid- to late-1970s, at the dawn of the personal computer (PC) age. At that time, PCs were few and far between, and a kid who owned a Commodore PET, a Tandy TRS-80, or an Apple was a rare and lucky kid indeed! Most big businesses used big mainframe computers to do the most time-consuming tasks of any business—accounting, payroll, and taxes. But even at this time period, most white-collar employees who worked in an office did not have a PC. Imagine that! It’s unheard-of today! Today, the first thing a new employee must have is a cubicle or an office with a PC. And, not just that, but a networked PC with Internet access.

Windows Phone 7 as a Game Platform?

There was a time not too many years ago when just having a PC was enough to do your work—programming, software engineering, computer-aided design (CAD), word processing, accounting. Even in the 1980s, it was rare for every employee to have a PC at his or her desk, and even more rare for families to have a PC in their homes. A lot of kids might have had a Nintendo Entertainment System (NES) or Sega Master System (SMS) or the older Atari 2600, all of which used cartridge-based games. A step up from these video game systems were the true PCs of the time, such as the Apple II, Commodore 64, Amiga, Atari 400/800, and Atari ST. No computer enthusiasts at the time used an IBM PC at home! MS-DOS was a terrible operating system compared to the other, more user-friendly ones. If you wanted to do programming, you would naturally gravitate to the consumer PCs, not the business-oriented IBM PC. Now, at the time, the Apple Macintosh was pretty expensive and the ordinary kid would prefer an Apple II, but that was the start of the Mac, back in the 1980s (although it has been completely redesigned several times before reaching the modern OS X).

Well, today the world sure is a different place. If we just ignore how powerful computers are today, just look at all the hand-held systems—they’re everywhere! The Nintendo DS family and the Sony PlayStation Portable (PSP) family are the two leading competitors of hand-held video game systems, and they can do almost anything that their big brothers (Nintendo Wii and Sony PS3) can do, including online play. These things are everywhere! You can’t walk through a store or a mall without seeing kids carrying some sort of mobile video game system with them, not to mention phones. And it’s not just kids, but adults have their toys too, like Apple iPhone, iPod, and iPad, for which some really great games are available! One of my favorites is Plants vs Zombies by PopCap Games. You can also get the game for Xbox 360, Mac, Windows, and Nintendo DS. And you know what? Some popular games are starting to come out for Windows Phone 7 because it’s fairly easy to port an Xbox 360 game to Windows Phone 7.

So what is Windows Phone 7 all about? Obviously, since you’re reading this book, you are interested in programming games for the device. That goes without saying, but what is development for this platform really like? What’s it all about? We have to ask ourselves these questions because developing a game that you want to be taken seriously requires a pretty big investment of time, if not money. Most likely, anyone looking at Windows Phone 7 for game development is already experienced with XNA Game Studio. If you have never used this development tool, the next hour will be helpful because we’ll be creating projects and working with Visual C# quite a bit. I’ll assume that you might not have any experience with Visual Studio, but I do not want to annoy experienced developers, so bear with me a bit while we cover the basics such as these!

History of the Platform

Windows Phone 7 follows a long history of mobile devices from Microsoft, dating clear back to the Pocket PC in 2000. Pocket PC competed directly with the market leader of the time, Palm. The Palm Pilot was arguably the progenitor of all handsized mobile computers today, including cellphones.

Interestingly enough, I would not consider Apple’s iPhone as an evolutionary leap beyond Palm Pilot—ignoring the many devices that have entered the market in the intervening years of the past decade. The iPhone does not follow in the lineage of “mobile computer” dating back to the Palm Pilot and Pocket PC because it was derived from Apple’s wildly successful iPod. The iPod should have been invented by Sony, the company responsible for the “Walkman” generation of portable music players. Everyone in the 1980s and early 1990s owned a “Walkman,” regardless of the brand, in the same vein that everyone has played with a “Frisbee,” despite these being brand names with competing companies making similar products. We Americans, due to targeted advertising, come to associate whole industries with a single product name, merely out of habit.

At any rate, you might have heard the term “podcast.” The term is rather generalized today to mean audio streamed or recorded in digital form for playback on a digital media player. But the concept was invented by Apple for the iPod and iTunes (including iTunes University), which now work with video files as well as audio files. While everyone was caught up in the Napster lawsuits, Apple was busy developing iTunes and began selling music in a revolutionary new way: per track instead of per album. Have you ever heard a catchy new song on the radio and wanted to buy it for your iPod, Microsoft Zune, Creative Zen, or similar media player? Well, in the past decade, you would buy the whole CD and then rip the tracks into MP3 with software such as Windows Media Player or Winamp. This point is debatable, but I would argue that Apple iTunes proved that digital music sales can be a commercial success, highly profitable both for the recording artists and for the service provider (iTunes). Amazon is probably the second case example that proves this is now a commercially successful way to sell music.

The point is, iPod was so successful that it evolved into the iPhone and iPad, and competing companies have been trying to keep up with Apple in both of these markets now for years! The iPod and its relatives are insanely great, which is why everyone wants one. More than a fashion statement, Apple understood what the consumer wanted and made it for them. What did customers want? Not a do-everything badly device, but a do-the-most-important-thing great device. In contrast, many companies hire “experts” to conduct consumer studies, and then spend millions trying to convince customers that they really want and need that product. This might be one good way to break into a relatively unknown market or to adjust the feature set of a product according to consumer interest. But the situation Apple finds itself in today is enviable, and with that comes emulation.

The previous iteration of Windows Mobile was called Windows Phone 6.5, and over a dozen hardware manufacturers and networks supported it, from Acer to HP to Samsung. Prior to that, Windows Phone 5 revolutionized the platform with a GPU (graphics processing unit) for 3D rendering.

The current Windows Phone 7’s operating system traces its roots directly back to the original Pocket PC operating system released in 2000. Pocket PCs came with a stylus, much like the one used on a Nintendo DS. This allows for precise input coordinates, necessary for apps like a spreadsheet (a portable version of Excel called Pocket Excel was available). However, stylus input can be tedious in today’s hustle-and-bustle environment, where it is more convenient to use a thumb to do things on the device’s touchscreen. Who wants to fish out a stylus just to tap a silly pop-up button (which Microsoft developers are notoriously fond of) when a thumb or another finger will do the trick?

The online capabilities of the Sega Dreamcast video game console were made possible thanks to Windows CE. If you look at the front of the Dreamcast case, you will find a Windows CE logo.

To get technical, Windows Phone 7 is based on the Windows Mobile operating system, a new name for the classic Windows CE operating system. Windows CE goes back quite a few years. “Pocket PC” was a marketing name for Windows CE 3.1. Developers at the time used Microsoft eMbedded Visual Tools 3.0 (see Figure 1.1) to develop for Windows CE 3.1. This was a modified version of Visual Studio 6 for Windows CE that was actually a remarkable development environment! It was stable, fully featured, and free! This might be considered an early predecessor of the Express Editions now made available free by Microsoft. At the time, there were many Pocket PC models available, but the most notable ones were from Casio, HP, Dell, and Compaq.

FIGURE 1.1 Microsoft eMbedded Visual C++ 3.0.
FIGURE 1.1 Microsoft eMbedded Visual C++ 3.0.

Microsoft supported game development on the Pocket PC (Windows CE 3.1) by providing a low-level library called the Game API. It was nowhere near as powerful as DirectX for rendering; but neither was the Game API at the slower level of the Windows GDI (graphics device interface). No, the Game API did give access to the actual bits of the video memory, making it possible to write a low-level blitter (a term derived from the “bit-block transfer” form of memory copying). Many developers worked on sprite renderers and game libraries using the Game API, and a book was published on the subject—Pocket PC Game Programming: Using the Windows CE Game API, by Prima-Tech—in 2001. Some copies are still floating around if you’re curious about “the early days” and the predecessor of WP7. At the time, developers had their choice of eMbedded Visual Basic or eMbedded Visual C++, but today we’re developing games for WP7 using XNA and C#. In that 2001 book is a rudimentary game library surrounding WinMain() and the other Windows core code necessary when working in C++, as well as integrated Game API built into a series of classes.

I created one published game using the library from that early book, an indie game called Perfect Match, shown in Figure 1.2. It was sold on mobile sites such as www. Handango.com. Since I lost contact with the artist who did all the renderings, the game could not be updated or ported to any newer systems. By the way, the screen resolution was 240×320 in portrait orientation, and most games were designed to be played this way; but you’ll note that many WP7 games require the player to tilt the device sideways (landscape orientation). This is something that was not common back in the Pocket PC days, but it makes sense now.

FIGURE 1.2 Perfect Match, a Pocket PC 2000 game.

Another example from the time period is the final sample game in the book, a multiplayer game called Pocket Air Hockey, shown in Figure 1.3. This was a quick game, but even now, looking back on it, I think the chat keypad and networking code were quite good for a book example. I used the Windows Sockets (winsock) library with threading. To develop the game, I had two Pocket PCs (a Casio Cassiopeia and an HP Jornada) each equipped with a Hawking CF LAN card plugged into the top expansion port with blue CAT5 network cables going into each one. Can you imagine that? (There were also 802.11b Wi-Fi cards available for the Compact- Flash adapter port.) I just don’t think anyone was really into developing multiplayer games for this platform at the time.

FIGURE 1.3 Pocket Air Hockey, a networked multiplayer game.
FIGURE 1.3 Pocket Air Hockey, a networked multiplayer game.

There was no single processor standard for the original Pocket PC 2000 devices, but three came to be used: Hitachi SH-3, NEC VR MIPS, and StrongARM. The ARM processor would become the single standard for Pocket PC 2002. The reason there have been so many releases in recent years, compared to the past, without significant updates to the core operating system (Windows CE) is that there’s a need to keep up with the aggressive cellphone market’s demand for change, even when change is not entirely necessary. When a company releases some trivial new feature in one of its phones, all competitors must come up with a compelling reason for customers to choose their phone instead. The carrier networks (T-Mobile, AT&T, and Verizon, primarily) also push hard for new devices and plans to maintain their customers and attract new customers. So, Windows Mobile 6 might not even be recognizable between 2007 and 2009, but the changes are primarily cosmetic, but also have to do with user input and application support. This market has been chaotic, to say the least! Table 1.1 is a historical list of releases for the platform.

History of Windows Mobile
TABLE 1.1 History of Windows Mobile
History of Windows Mobile
TABLE 1.1 History of Windows Mobile

Windows Phone 7 was planned for release in 2009 with a core based on Windows CE 5.0—a core dating back to 2005. The core was just too old, so development failed. At that point, a stopgap product was released (Windows Phone 6.5) while Windows Phone 7 went back to the drawing board. The Windows Mobile team ended up rebuilding the new platform from scratch around the new Windows CE 6.0 core for release the following year (2010).

Hardware Specifications

What we have today in the WP7, a completely new operating system built from the ground up around the Windows CE 6.0 core, is a modern touch-enabled architecture with no resemblance to the Windows desktop computer operating system. It took many years, but Microsoft finally perfected the platform! No longer must mobile users tap with a stylus. A sample phone built by Samsung and connected to the AT&T network is shown in Figure 1.4. WP7 competes directly with two other smartphones in the industry today: Apple iPhone and Google Android. Apple is a closed architecture, meaning only Apple builds iPhone devices. WP7 and Android, on the other hand, are not so much mobile devices as they are operating systems. That is why there are many devices available in the Android and WP7 format—but there is only one iPhone. From a developer’s point of view, this openness makes life more difficult. Android, for instance, may be too open, with many different screen sizes and hardware specs. Developing a game for iPhone? That’s a piece of cake, as far as specifications go, because there is only one (although, admittedly, adjustments to the settings are required for iPad due to its larger screen resolution).

Table 1.2 shows the common hardware specifications among most of the models available at the time of this writing. The most notable thing about the specifications is that they now follow a basic standard across all manufacturers. Apple has proven that extreme openness and flexibility are not always desirable traits in mobile hardware. One of the difficulties facing Android developers today is the need to support many different hardware devices in a single code base. Windows Mobile developers had to deal with a similar problem in Windows Phone 6.4 and earlier versions, but as you can see, WP7 has a much simpler subset of hardware specifications. This is a good thing for developers, greatly simplifying the code, allowing developers to focus on game design and gameplay rather than hardware idiosyncrasies among the different makes and models.

A Windows Phone 7 device built by Samsung.
FIGURE 1.4 A Windows Phone 7 device built by Samsung.
Windows Phone 7 Hardware Specifications
TABLE 1.2 Windows Phone 7 Hardware Specifications

WP7 is an awesome integration of many technologies that have evolved over the years, beginning with the early Windows CE and Pocket PC devices, to the modern, powerful smartphone of today with advanced 3D rendering capabilities that truly bring cutting-edge gaming into the palm of your hand.

The XNA Game Execution Model

XNA uses a game loop that is generated by the design tools. The life cycle for a game consists of four main stages, as shown in Figure 1.

The life cycle for an XNA game

The game first initializes and then loads content such as sprites, images, sounds, and other components of the game. It then initiates the game loop. The game loop consists of two processes that run asynchronously: code that draws the frame containing the complete screen to a buffer, and code that updates the screen from the buffer. This loop runs until the user closes the game, at which point the content is unloaded.

Draw and Update are executed at different rates. Draw is executed as frequently as possible based on the maximum frame rate that the device can provide, whereas Update is executed at a regular rate. The draw rate should generally be higher than the update rate.

For more information about creating games using XNA, see “Getting Started with XNA Game Studio Development” on MSDN® (http://msdn.microsoft.com/en-us/library/bb203894.aspx). For a walkthrough of creating a simple game using XNA, see “Your First Game: Microsoft XNA Game Studio in 2D” at on MSDN (http://msdn.microsoft.com/en-us/library/bb203893.aspx).

 

Create a New File

To work with data in Office 2010, you must create a file in which to store it. If the file you want to create is a Word document, an Excel workbook, an Access database, a PowerPoint presentation or a Publisher publication, you create a new file using the Getting Started screen. You are given the option of creating a blank file or basing the file on an existing template. To create a new item in Outlook, whether it is an e-mail message, a calendar appointment, a contact or a task item, you use the Ribbon.

Create a New Word, Excel, PowerPoint, Access or Publisher File

Create a New Word, Excel, PowerPoint, Access or Publisher File

  1. Click the File tab.
  2. Click New.
    The New screen appears.
  3. Click the type of file that you want to create.
  4. Click Create.
    The new file opens.

Create a New Outlook Item

Create a New Outlook Item

  1. In the lower left corner of the Outlook window, click the type of item you want to create – Mail, Calendar, Contact or Task.
  2. Click the New type button, where type is the type of item. For example, if you are creating a Mail item, the button is labelled “New E-mail”. If you are creating a Calendar item, the button is labelled “New Appointment”, “New Meeting” and so on.
    The new item opens.

To create a new file from a template, simply click the desired template in the New screen.

 

If you are connected to the Internet, you can access more Office templates. Simply click a template category under Office.com Templates in the New screen to display a list of available templates in the selected category; double-click one to download the template and apply it to a new file.

Resources for Web and Service Developers

Windows Phone 7 includes comprehensive web browsing capabilities. In addition, ASP.NET allows you to detect the client device type making a request so that you can provide the content in a format and style appropriate to the device. For information about how Windows Phone 7 supports web browsing, and how to maximize your application experiences on Windows Phone 7, see Designing Web Sites for Phone Browsers (a PDF document) available from the Microsoft Download
Center (http://go.microsoft.com/?linkid=9713253).

For information about mobile device support in ASP.NET, see “ASP.NET for Mobiles” on the Microsoft ASP.NET website
(http://www.asp.net/mobile/) and “Walkthrough: Adding Support for Devices” on MSDN (http://msdn.microsoft.com/en-us/library/wa642f6e(VS.71).aspx).

Mobile phone applications aimed at the enterprise and for consumer use will usually require access to remote services to be able to obtain information, exchange data, or synchronize content. Typically, on the Microsoft platform, you will implement these services using the Windows Communication Foundation (WCF) technology that is part of the .NET Framework. For information about WCF, see “Windows Communication Foundation” on MSDN (http://msdn.microsoft.
com/en-us/netframework/aa663324.aspx).

A common approach for delivering data or exposing services to mobile devices such as Windows Phone 7 is by using the Representational State Transfer (REST) architectural style for the service. For information about REST-based services, see “REST in Windows Communication Foundation (WCF)” on MSDN (http://msdn.microsoft.com/en-us/netframework/cc950529.aspx) and “An Introduction To RESTful Services With WCF” in MSDN Magazine (http://msdn.microsoft.
com/en-us/magazine/dd315413.aspx). For a definition of the way that REST-based services work, see “Canonical REST Entity Service” on the Microsoft .NET website (http://code.msdn.microsoft.com/cannonicalRESTEntity).

In other cases, such as exchanging small volumes of data between the client and server or calling specific methods on the server, you may decide to use SOAP instead. For more information about WCF, see “Getting Started with WCF” on MSDN (http://msdn.microsoft.com/en-gb/library/ee354180.aspx).