Saturday, November 06, 2010

Write Windows Phone 7 game – for beginners (Part II)

Let’s start with game design. Our decision was a light version of blackjack game. “Light” means here: we implement only a subset of the real blackjack game. (Anyway you can improve the game logic using the sample source code later to narrow the “real” game).

First, we design the gambling table as the only frontend of the game:

Untitled

  • dealer: the picture of the dealer (computer)
  • player: the picture of player (human)
  • cardstock: the picture of the playing cards stock used to hit cards by the player if “touched”
  • stand: the picture used as “stand” button if “touched”
  • dealer cards: the sequence of cards hit by dealer
  • player cards: the sequence of cards hit by player
  • score dealer: the current score of the dealer
  • score player: the current score of the player

So far so good, we reach the first part of quick start into WP7 game programming: display information.

Display information in Windows Phone 7 games

The display functionality is encapsulated in the method Draw():

/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.Green); // we paint the table green

    // TODO: Add your drawing code here

    base.Draw(gameTime);
}

The method is described here: http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.draw.aspx
”Called when the game determines it is time to draw a frame. Override this method with game-specific rendering code.”

We will display data using the class SpriteBatch described here:

An instance variable of the class SpriteBatch:

SpriteBatch spriteBatch;

will do the display job for us.

SpríteBatch instance does display the data in three steps:

  • Begin() initiates begin of sprite operations ( = display actions)
  • the instance of SpriteBatch performs the display actions
  • End() finishes the sprite operations

So referring to the UI model designed above, the Draw() function looks like follows:

/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.DarkGreen);

    // begin the display actions
    spriteBatch.Begin();

    // draw dealer's picture
    drawDealer();
    // draw player's picture
    drawPlayer();
    // draw card stock
    drawStock();
    // draw player's cards
    drawPlayerCards();
    // draw dealer's cards
    drawDealerCards();
    // draw game controls
    drawControls();
    // draw game score
    drawScore();
    // draw game result
    drawResult();

    // end display actions
    spriteBatch.End();

    base.Draw(gameTime);
}

There are two basic display operations implemented in this game: display a picture (called texture in terms of WP7 game) and display a string of text.

Display pictures

The most popular task to display information in a game is to display a picture. The pictures in WP7 games are called textures. The textures can be displayed by spriteBatch, but have to be loaded before from game content.

The loading of textures used in the game is realized usually in LoadContent() method:
 http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.loadcontent.aspx

This method is called when game resources need to be (re)loaded – even if DeviceReset() is called.

Loading of pictures looks like follows:

textureCardBack = Content.Load<Texture2D>("cardBack");

where cardBack is the name of the graphic resource saved as a picture (PNG, BMP etc.) file in game content project:

image

During the Draw() method call the previously loaded texture can be dispalyed by spriteBatch as follows:

spriteBatch.Draw(textureCardBack, stockPosition, Color.White);

The Draw() method of SpriteBatch used here takes three parameters:

  • texture (picture) to be displayed
  • screen position to display the picture
  • color to tint the picture (we use Color.White to avoid tinting)

Adding pícture to game content

To add a picture to the game use “Add” –> “New Item…” command from the context menu in the game content project:

image

Then select “Bitmap file” and edit it.

Alternatively use “Add” –> “Existing item…” to add an existing graphic file

Display text

SpriteBatch() can also display text messages. We use this functionality to display scores:

spriteBatch.DrawString(scoreFont, scoreDealer.ToString(), DealerScorePosition, color);

The method DrawString() used here takes four parameters:

  • font to be used (this font must be loaded before the call – usually in the LoadContent() method similar to loading textures)
  • text to display (in the sample above – dealer’s score as string)
  • screen position to display the text
  • text display color

Adding font to game content

To add a font to the game use “Add Item…” command from the context menu in the game content project as described above (adding picture to game).

Then select “Sprite Font” - a new font description file will be added to game content:

image

The spritefont file is a XML based font description file:

<?xml version="1.0" encoding="utf-8"?>
<!--
This file contains an xml description of a font, and will be read by the XNA
Framework Content Pipeline. Follow the comments to customize the appearance
of the font in your game, and to change the characters which are available to draw
with.
-->
<XnaContent xmlns:Graphics="Microsoft.Xna.Framework.Content.Pipeline.Graphics">
  <Asset Type="Graphics:FontDescription">

    <!--
    Modify this string to change the font that will be imported.
    -->
    <FontName>Segoe UI Mono</FontName>

    <!--
    Size is a float value, measured in points. Modify this value to change
    the size of the font.
    -->
    <Size>36</Size>

    <!--
    Spacing is a float value, measured in pixels. Modify this value to change
    the amount of spacing in between characters.
    -->
    <Spacing>0</Spacing>

    <!--
    UseKerning controls the layout of the font. If this value is true, kerning information
    will be used when placing characters.
    -->
    <UseKerning>true</UseKerning>

    <!--
    Style controls the style of the font. Valid entries are "Regular", "Bold", "Italic",
    and "Bold, Italic", and are case sensitive.
    -->
    <Style>Bold</Style>

    <!--
    If you uncomment this line, the default character will be substituted if you draw
    or measure text that contains characters which were not included in the font.
    -->
    <!-- <DefaultCharacter>*</DefaultCharacter> -->

    <!--
    CharacterRegions control what letters are available in the font. Every
    character from Start to End will be built and made available for drawing. The
    default range is from 32, (ASCII space), to 126, ('~'), covering the basic Latin
    character set. The characters are ordered according to the Unicode standard.
    See the documentation for more information.
    -->
    <CharacterRegions>
      <CharacterRegion>
        <Start>&#32;</Start>
        <End>&#126;</End>
      </CharacterRegion>
    </CharacterRegions>
  </Asset>
</XnaContent>


Edit the font parameters regarding text display requirements.

Play sound

Another way to provide user with information is playing sounds. A sound to play must be loaded from the game content the same way as we do for textures or fonts:

cardDownSound = Content.Load<SoundEffect>("cardDown");

where cardDown is the name of the sound file (usually WAV encoded) enclosed in game content:

image

To play the sound at the drawing time or in other game situations just use Play() method:

cardDownSound.Play();

…more to come…

29 comments:

Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...

Awesome, that’s exactly what I was scanning for! You just spared me alot of searching around

Anonymous said...

Its awesome all of the time to view how folks can compose wonderful stuff about people topics! Thank you and I ve bookmarked you

Anonymous said...

this website is my inspiration , really superb style and design and perfect written content .
Assisted me a lot, just what I was looking for : D.

Anonymous said...

Очень занятные мысли, хорошо рассказано, все просто таки разложено по полкам :)

Крутой сайт! Все умно сделано.

Anonymous said...

Hi this theme is hugely concerning. Keep it going guy !

Anonymous said...

Hi !!! Good job!
Wuzzap?

Anonymous said...

Hello. It is great that at least you pour more light on this issue. Thanks.

Anonymous said...

I twitt it. My twitter on name Alexander Belluchi. You can comment this post there too.

Anonymous said...

So what? I want to share this post on Facebook, I am under name John McCain there.

Anonymous said...

Thanks. I retwit it on my Twiiter
Bob Peters, CA

Anonymous said...

Good Article

Anonymous said...

Good Article

Anonymous said...

исходники
-----

winmike said...

с удовольствием - мейлбокс?

Anonymous said...

I am glad to be a visitor of this utter web site! , appreciate it for this rare info ! .

Anonymous said...

I am sorry, I can help nothing. But it is assured, that you will find the correct decision.|

Anonymous said...

Hack again?!

Anonymous said...

I apologize that distracting , but I have some reason crookedly displayed in your browser , and some buttons do not see what could be wrong?

winmike said...

can post the screenshot?

Anonymous said...

Certainly. And I have faced it.
Merry Christmas! :)

Anonymous said...


Hi! Would you mind if I share your blog with my twitter group?

Anonymous said...


An attention-grabbing dialogue is price comment.

Anonymous said...


Some really select articles on this internet site , bookmarked)))

Anonymous said...


Definitely, what an excellent site and also informative posts, I definitely will bookmark your site. Have a great awsome day!

Anonymous said...


Maybe you could write next articles referring to this article.

Anonymous said...


very nice post, i certainly love this website, keep on it

Anonymous said...


Excellent post. I certainly love this website. Keep it up!

Anonymous said...


Hello Generally there. I found your website using google. This is certainly a new very well written article.