Chapter 6. GamerServices

The GamerServices namespace within Microsoft.Xna.Framework is one of the most, er, entertaining collections of classes available in XNA. It gives you access to the Xbox Live avatar, friends, and player settings! Because this action-packed namespace has so much to offer, we will spend quite a bit of time here and cover every detail. First, this chapter has a quick reference to the GamerServices namespace with all of its great classes, structures, and enumerations. Then, we jump into the code and experiment with these great features!

As a side note, most of the features covered in this chapter require an Xbox Live Gold account, and it goes without saying that you need to have your Xbox 360 connected to the Net in order to retrieve the information provided by these features in the GamerServices namespace. If you don’t have your Xbox 360 online, most of the examples in this chapter will not work. As for the Windows version of the examples, these features don’t make much sense on Windows, so there will likely be some null values and connectivity failures even though the code will still compile for the Windows platform. This chapter is primarily focused on the Xbox 360. Here’s what I’ll be covering:

  • GamerServices classes

  • GamerServices interfaces

  • GamerServices structures

  • GamerServices enumerations

  • GamerProfile Demo program

Microsoft.Xna.Framework.GamerServices Reference

GamerServices is one of the largest namespaces in the XNA Framework. This namespace provides information about the gamer profile, which is basically an Xbox Live membership account with all the stored data about that player’s experiences on Xbox Live, such as games played, achievements, friends, avatar, gamer profile picture, game rank leaderboards, and related information. There’s a lot of information to cover in this chapter, which begins with a quick reference to the most important details first, followed by a sample program.

Note

Microsoft disclaims the availability of the GamerServices features on the Windows platform with this comment: “Games for Windows Live is unavailable to finished games. This functionality is not included in the redistributable version of the XNA Framework. A game that attempts to use these components without XNA Game Studio installed will result in a GamerServicesNotAvailableException.”

Classes

Following are the classes found within the GamerServices namespace.

Achievement

public sealed class Achievement

Describes a single achievement, including the achievement name, description, picture, and whether it has been achieved by the currently signed-in gamer. Unfortunately, you can’t use achievements in indie games unless they have been officially published on Xbox Live (which involves a contract with Microsoft).

Note

Microsoft disclaimer: “This class and all related methods and properties will only retrieve a calculated result for titles approved to access Xbox Live services through the Xbox Live Registered Developer Program. For Xbox Live Indie games, the properties in this class will not return a calculated result and related methods will report a NotSupportedException.”

Public Properties

 

Description

Gets the localized achievement description string.

DisplayBeforeEarned

Gets whether this achievement should be displayed before it is earned.

EarnedDateTime

Gets the date at which this achievement was earned.

EarnedOnline

Gets whether this achievement was earned while online.

GamerScore

Gets the amount of gamer score awarded for earning this achievement.

HowToEarn

Gets the localized description of the steps necessary to earn the achievement.

IsEarned

Gets whether the current player has earned this achievement.

Key

Gets the achievement key string.

Name

Gets the localized achievement name string, for display to the user.

Public Methods

 

GetPicture

Gets the image associated with this achievement.

AchievementCollection

Collection holding the achievements belonging to a signed-in gamer.

Note

Microsoft disclaimer: “For Xbox Live Indie games, the properties in this class will not return a calculated result and related methods will report a NotSupportedException.”

Public Properties

 

Count

Gets the number of objects in the collection.

Item

Properties that retrieve an achievement from the collection.

Public Methods

 

GetEnumerator

Gets an enumerator that can iterate through this Achievement Collection.

AvatarAnimation

Provides methods and properties for animating an avatar using standard animations (for example, celebrate).

Public Properties

 

BoneTransforms

Gets the current position of the bones at the time specified by CurrentPosition.

CurrentPosition

Gets or sets the current time position in the animation.

Expression

Gets the expression of the related animation at the current time position.

IsDisposed

Gets the disposed state of the avatar animation.

Length

Gets the length of the current animation.

Public Methods

 

Update

Updates the current time position of the avatar animation.

AvatarDescription

Provides access to the methods and properties of the description data for an avatar.

Public Properties

 

BodyType

Gets the body type of the avatar based on the description data.

Description

Internal description buffer of the avatar, stored as a byte buffer.

Height

Height of the avatar, from the feet to the top of the head.

IsValid

Determines whether the internal data buffer is valid.

Public Methods

 

BeginGetFromGamer

Begins the process of getting an AvatarDescription object for a specified gamertag.

CreateRandom

Creates an AvatarDescription object with random gender, features, and clothing.

EndGetFromGamer

Ends the process of getting an AvatarDescription object for a specified gamertag.

Public Events

 

Changed

Occurs when a gamer’s avatar changes.

AvatarRenderer

Provides properties and methods for rendering a standard avatar.

Public Fields

 

BoneCount

Number of bones in the avatar model.

Public Properties

 

AmbientLightColor

Gets or sets the color of the ambient light used by the avatar renderer.

BindPose

Gets the collection of bind pose positions for each bone of the avatar model.

IsLoaded

Gets the loaded state of the avatar.

LightColor

Gets or sets the color of the directional light used by the avatar renderer.

LightDirection

Gets or sets the direction of the directional light used by the avatar renderer.

ParentBones

Collection of the parent indices for each bone in the related BindPose collection.

Projection

Gets or sets the projection matrix for the avatar.

State

Gets the state of the avatar.

View

Gets or sets the view matrix for the avatar.

World

Gets or sets the world matrix for the avatar.

Public Methods

 

Draw

Draws the avatar to the current render target.

FriendCollection

Represents the complete friends list of a local gamer.

Public Properties

 

Count

Gets the number of elements contained in the ReadOnlyCollection <(Of <(T>)>) instance.

Item

Gets the element at the specified index.

Protected Properties

 

Items

Returns the IList that the ReadOnlyCollection wraps.

Public Methods

 

GetEnumerator

Returns a strongly typed GamerCollection. GamerCollectionEnumerator structure that can iterate through a GamerCollection.

FriendGamer

Provides the presence information of a friend of the local gamer.

Public Properties

 

DisplayName

Gets the display name string for the gamer.

FriendRequest-ReceivedFrom

Gets whether the local gamer who requested the friends list has received a friend request from this gamer.

FriendRequestSentTo

Gets whether the local gamer who requested the friends list has sent a friend request to this gamer.

Gamertag

Gets the gamertag string.

HasVoice

Gets whether this friend currently has voice capability.

InviteAccepted

Gets whether this friend has accepted an invitation from the local gamer who requested the friends list.

InviteReceivedFrom

Gets whether the local gamer who requested the friends list has received an invitation from this friend.

InviteRejected

Gets whether this friend has rejected an invitation from the local gamer who requested the friends list.

InviteSentTo

Gets whether the local gamer who requested the friends list has sent an invitation to this friend.

IsAway

Gets whether this friend is currently away from the computer or console.

IsBusy

Gets whether this friend is currently busy.

IsJoinable

Gets whether this friend is currently in a public session that can be joined.

IsOnline

Gets whether this friend is currently online.

IsPlaying

Gets whether this friend is currently playing a game.

LeaderboardWriter

Gets an object that can be used to write leaderboard statistics for this gamer.

Presence

Gets a presence string describing what this friend is currently doing.

Tag

Gets or sets a custom object that can be used to attach arbitrary user-defined data to the gamer.

Public Methods

 

BeginGetProfile

Starts an asynchronous profile read operation.

EndGetProfile

Ends an asynchronous profile read operation.

GetProfile

Reads profile data for this gamer.

GameDefaults

Describes a gamer’s preferred settings.

Public Properties

 

AccelerateWithButtons

Gets whether the gamer prefers to use controller buttons to accelerate in racing games.

AutoAim

Gets whether the title should automatically correct the gamer’s aim.

AutoCenter

Gets whether the title should automatically center the view when the gamer moves.

BrakeWithButtons

Gets whether the gamer prefers to use controller buttons to brake in racing games.

Controller Sensitivity

Gets the preferred controller sensitivity setting for this gamer.

GameDifficulty

Gets the preferred difficulty setting for this gamer.

InvertYAxis

Gets whether the gamer prefers to invert the y-axis input of the controller.

ManualTransmission

Gets whether the gamer prefers to drive a manual shift transmission in racing games.

MoveWithRight ThumbStick

Gets whether the gamer prefers to move using the right thumbstick.

PrimaryColor

Gets the preferred color for the player character.

RacingCameraAngle

Gets the gamer’s preferred camera angle for racing games.

SecondaryColor

Gets a secondary color selection for the player character.

Gamer

Abstract base class for types that represent game players (profiles that have an associated gamertag). The concrete types SignedInGamer and NetworkGamer derive from this. For the NetworkGamer class, see Chapter 10, “Net.”

Public Properties

 

DisplayName

Gets the display name string for the gamer.

Gamertag

Gets the gamertag string.

LeaderboardWriter

Gets an object that can be used to write leaderboard statistics for this gamer.

SignedInGamers

Represents a collection of all gamers on the local system.

Tag

Gets or sets a custom object that can be used to attach arbitrary user-defined data to the gamer.

Public Methods

 

BeginGetFrom Gamertag

Begins the process of getting a Gamer object for a specified gamertag.

BeginGetPartner Token

Begins the asynchronous process of getting the partner token for this gamer.

BeginGetProfile

Starts an asynchronous profile read operation.

EndGetFrom Gamertag

Ends the process of getting a Gamer object for a specified gamertag.

EndGetPartner Token

Retrieves the results from an asynchronous request for the partner token for this gamer.

EndGetProfile

Ends an asynchronous profile read operation.

GetFromGamertag

Returns a Gamer object for the specified gamertag.

GetPartnerToken

Gets the partner token for this gamer.

GetProfile

Reads profile data for this gamer.

GamerCollection

Represents a collection of gamers. This collection cannot be modified and is updated automatically during the call to Update(). This class inherits from ReadOnlyCollection and uses the GamerCollectionEnumerator structure, but exposes no new properties or methods of its own.

GamerPresence

Provides properties to set the rich presence state for a locally signed-in gamer profile.

Public Properties

 

PresenceMode

Gets or sets the current presence mode for this gamer.

PresenceValue

Gets or sets a custom presence value.

GamerPrivilegeException

Thrown if a gamer services or multiplayer API is called without a valid, signed-in profile. This class exposes no new properties or methods beyond its base class.

GamerPrivileges

Describes what operations a gamer is allowed to perform. GamerPrivileges can be defined by parental control settings, and will also be set automatically in response to things like age, region, and whether the gamer has a Live Gold or Live Silver account. Games do not need to explicitly check privileges because a GamerPrivilegeException will be thrown if they try to perform an unsupported operation, but these privilege bits may be useful to detect that an operation is unavailable before calling it so the relevant menu option can be grayed out.

Public Properties

 

AllowCommunication

Checks whether this gamer is allowed to send and receive communications using voice, text, messaging, or game invites.

AllowOnlineSessions

Checks whether this gamer is allowed to play in online multiplayer sessions.

AllowPremiumContent

Checks whether this gamer is allowed to access premium content.

AllowProfileViewing

Checks whether this gamer is allowed to view the profiles of other gamers.

AllowPurchaseContent

Checks whether this gamer is allowed to purchase content from Live Marketplace.

AllowTradeContent-

Checks whether this gamer is allowed to trade content with other gamers.

AllowUserCreatedContent

Checks whether this gamer is allowed to access user content that was created by other gamers.

GamerProfile

Profile settings describing information about a gamer such as the gamer’s motto, reputation, and picture. This data is accessible for both locally signed-in profiles and remote gamers that you are playing with in a multiplayer session.

Public Properties

 

GamerScore

Gets the GamerScore of this gamer.

GamerZone

Gets the GamerZone setting.

Motto

Gets the gamer motto string.

Region

Gets the region of this gamer.

Reputation

Gets the gamer reputation, as a number of stars ranging 0 to 5.

TitlesPlayed

Gets the number of titles this gamer has played.

TotalAchievements

Gets the total number of achievements this gamer has obtained.

Public Methods

 

GetGamerPicture

Gets the gamer picture associated with this profile.

GamerServicesComponent

Wraps the functionality of the GamerServicesDispatcher.

Public Methods

 

Initialize

Initializes the GamerServicesDispatcher.

Update

Updates the GamerServicesDispatcher.

GamerServicesDispatcher

Implements the Windows-specific portion of a GamerServicesDispatcher class.

Public Properties

 

IsInitialized

Determines whether Initialize has been called.

WindowHandle

Gets or sets the handle to the underlying game window.

Public Methods

 

Initialize

Initializes gamer-services functionality for the game, automatically choosing the most appropriate gamer-service type for the platform.

Update

Updates the status of gamer services and raises related events.

GamerServicesNotAvailableException

Thrown if the gamer services system cannot be successfully initialized.

GameUpdateRequiredException

The exception thrown when a game (title) update is required in order to use Xbox Live.

Guide

Provides access to the Guide user interface.

Public Properties

 

IsScreenSaverEnabled

Gets or sets the current state of the screen saver.

IsTrialMode

Determines whether the game is running in limited trial mode.

IsVisible

Determines whether a Guide user-interface screen is active.

NotificationPosition

Determines where notifications appear on the screen.

SimulateTrialMode

Allows titles to simulate trial mode restrictions when testing using the development configuration.

Public Methods

 

BeginShowKeyboardInput

Overloads for showing the software keyboard interface asynchronously.

BeginShowMessageBox

Begins the process of displaying a message box with the specified parameters.

DelayNotifications

Delays system notifications for the specified amount of time.

EndShowKeyboardInput

Ends the display of the keyboard input dialog box.

EndShowMessageBox

Ends the display of a message box.

ShowComposeMessage

Shows the Compose Message user interface.

ShowFriendRequest

Shows the Friend Request user interface.

ShowFriends

Shows the Friends user interface.

ShowGameInvite

Overloads to display the Game Invitation user interface.

ShowGamerCard

Shows the Gamer Card user interface.

ShowMarketplace

Displays the Marketplace user interface.

ShowMessages

Shows the Messages user interface.

ShowParty

Shows the Xbox Live Party screen.

ShowPartySessions

Shows the Play with Party Member screen.

ShowPlayerReview

Shows the Player Review user interface.

ShowPlayers

Shows the Players user interface.

ShowSignIn

Shows the user interface a gamer uses for signing into Xbox Live.

GuideAlreadyVisibleException

Thrown if an attempt is made to display a component of the Guide user interface when a Guide component is already displayed.

InviteAcceptedEventArgs

Represents the arguments passed to an InviteAccepted event.

Public Properties

 

Gamer

The signed-in gamer who is accepting the game invitation.

IsCurrentSession

Indicates if the invitation is for the current local session.

LeaderboardEntry

Class representing a single row of a leaderboard, holding all the information a specific gamer has uploaded to the board.

Public Properties

 

Columns

Provides access to the columns for this leaderboard entry.

Gamer

Provides access to gamer information for this leaderboard entry.

Rating

Provides access to the rating associated with this leaderboard entry.

LeaderboardReader

Reads data from leaderboards.

Public Properties

 

CanPageDown

Provides information about whether there are more leaderboard entries after the current page of entries.

CanPageUp

Provides information about whether there are more leaderboard entries before the current page of entries.

Entries

Gets the collection of leaderboard entries for the leaderboard.

LeaderboardIdentity

The identity of the leaderboard.

PageStart

Gets the index of the leaderboard entry at the start of the current page.

TotalLeaderboardSize

Provides information about the total number of entries in the leaderboard.

Public Methods

 

BeginPageDown

Begins an asynchronous read of the page of leaderboard data after the current page.

BeginPageUp

Begins an asynchronous read of the page of leaderboard data before the current page.

BeginRead

Methods for reading a leaderboard asynchronously.

EndPageDown

Checks the result of an asynchronous PageDown operation.

EndPageUp

Checks the result of an asynchronous PageUp operation.

EndRead

Checks the result of an asynchronous Read operation.

PageDown

Reads the next page of leaderboard data synchronously.

PageUp

Reads the previous page of leaderboard data synchronously.

Read

Method for synchronous reading of leaderboard data.

LeaderboardWriter

Records leaderboard data for players in a NetworkSession. Data can be written at any time during gameplay, but is only flushed to the server when the host calls EndGame. Data may be written for both local and remote gamers using the following rules:

  • Ranked sessions can write to both arbitrated and non-arbitrated leaderboards.

  • Other session types can only write to non-arbitrated leaderboards.

  • Arbitrated statistics should be written by all machines for all gamers.

  • Non-arbitrated statistics should only be written by their local machine.

  • In ranked sessions, all machines should report TrueSkill for all gamers.

  • In other session types, only the host should report TrueSkill data.

  • Leaderboards can only be written while in a NetworkSession, and while in the gameplay state rather than in the lobby. To write scores from a single-player game, create a session using NetworkSessionType. LocalWithLeaderboards.

Public Methods

 

GetLeaderboard

Gets a leaderboard entry that can be used to write to a specified leaderboard.

NetworkException

Thrown if there is a network-communications failure.

NetworkNotAvailableException

Thrown if a network connection is unavailable.

PropertyDictionary

Holds a set of properties used to define presence states or leaderboard column values.

Public Properties

 

Count

Gets the number of elements contained in this PropertyDictionary.

Item

Gets or sets the element with the specified key.

Public Methods

 

ContainsKey

Determines whether the PropertyDictionary contains an element with the specified key.

GetEnumerator

Returns an enumerator that iterates through a collection of key/value pairs that represent elements in the PropertyDictionary.

GetValueDateTime

Gets the value of the property with the specified key, as a System. DateTime.

GetValueDouble

Gets the value of the property with the specified key, as a System.Double.

GetValueInt32

Gets the value of the property with the specified key, as a System.Int32.

GetValueInt64

Gets the value of the property with the specified key, as a System.Int64.

GetValueOutcome

Gets the value of the property with the specified key, as a LeaderboardOutcome.

GetValueSingle

Gets the value of the property with the specified key, as a System.Single.

GetValueStream

Gets the value of the property with the specified key, as a System.IO.Stream.

GetValueString

Gets the value of the property with the specified key, as a System.String.

GetValueTimeSpan

Gets the value of the property with the specified key, as a System.TimeSpan.

SetValue

Method to set the value of the property with the specified key.

TryGetValue

Determines if a value for the specified key exists in the PropertyDictionary.

SignedInEventArgs

Represents the arguments passed to a SignedIn event.

Public Properties

 

Gamer

Gets the gamer who just signed in.

SignedInGamer

Represents a gamer (a profile that has an associated gamertag) on the local system. This class inherits from the abstract Gamer class, so refer to that class for more details.

Public Properties

 

GameDefaults

Describes a gamer’s preferred settings.

IsGuest

Determines whether the gamer is the guest of an Xbox Live–enabled profile.

IsSignedInToLive

Determines whether the gamer has an Xbox Live–enabled profile.

PartySize

Gets the current party size.

PlayerIndex

Gets the index of the gamer.

Presence

Gets an object that may be used to set the rich presence state for this gamer.

Privileges

Describes what operations a gamer is allowed to perform.

Public Methods

 

BeginAwardAchievement

Starts an asynchronous operation to award an achievement to a locally signed-in gamer.

BeginGetAchievements

Starts an asynchronous achievement query operation.

EndAwardAchievement

Ends an asynchronous achievement award operation.

EndGetAchievements

Ends an asynchronous achievement query operation.

GetAchievements

Returns the collection of all achievements that may be earned by this gamer.

GetFriends

Reads the friends list of this local gamer. This includes both the gamertags of the friends and their current presence information.

IsFriend

Queries whether the specified gamer is a friend of this local gamer.

IsHeadset

Determines if the microphone associated with this signed-in gamer is a headset.

Public Events

 

SignedIn

Occurs when a new gamer signs into the local system.

SignedOut

Occurs when a gamer signs out on the local system.

SignedInGamerCollection

Represents a collection of gamers on the local system.

Public Properties

 

Item

Gets a specific SignedInGamer object.

SignedOutEventArgs

Represents the arguments passed to a SignedOut event.

Public Properties

 

Gamer

Gets the gamer that just signed out.

Interfaces

The following interface is found in the GamerServices namespace.

IAvatarAnimation

Provides methods and properties for animating an avatar using custom animations.

Public Properties

 

BoneTransforms

Gets the current position of the bones at the time specified by CurrentPosition.

CurrentPosition

Gets or sets the current time position in the animation.

Expression

Gets the expression of the related animation at the current time position.

Length

Gets the length of the current animation.

Public Methods

 

Update

Updates the current time position of the avatar animation.

Structures

The following structures are found in the GamerServices namespace.

AvatarExpression

Contains the various components of the avatar’s face, such as the left and right eyebrows.

Public Properties

 

LeftEye

Gets or sets the current texture for the avatar’s left eye.

LeftEyebrow

Gets or sets the current texture for the avatar’s left eyebrow.

Mouth

Gets or sets the current texture for the avatar’s mouth.

RightEye

Gets or sets the current texture for the avatar’s right eye.

RightEyebrow

Gets or sets the current texture for the avatar’s right eyebrow.

GamerCollection.GamerCollectionEnumerator

Provides the ability to iterate through the gamers in a GamerCollection.

Public Properties

 

Current

Gets the current element in the GamerCollection.

Public Methods

 

MoveNext

Advances the enumerator to the next element of the GamerCollection.

LeaderboardIdentity

Contains leaderboard identity information for a particular leaderboard.

Public Properties

 

GameMode

Provides access to the game mode for this leaderboard identity.

Key

The key string associated with this leaderboard identity.

Public Methods

 

Create

Creates a leaderboard identity.

Enumerations

Following are the enumerations in the GamerServices namespace.

AvatarAnimationPreset

Defines standard animations for avatars. Note that additional animations can be downloaded from the XNA Web site as a collection, as can a sample bone structure mesh for use in creating your own custom avatar animations.

Celebrate

Gender-neutral, celebrating.

Clap

Gender-neutral, applauding.

FemaleAngry

Female, angry.

FemaleConfused

Female, confused.

FemaleCry

Female, cry.

FemaleIdleCheckNails

Female, checking nails.

FemaleIdleFixShoe

Female, fixing shoe.

FemaleIdleLookAround

Female, looking around.

FemaleIdleShiftWeight

Female, shifting weight from one foot to another.

FemaleLaugh

Female, laughing.

FemaleShocked

Female, shocked or surprised.

FemaleYawn

Female, yawning.

MaleAngry

Male, angry.

MaleConfused

Male, confused.

MaleCry

Male, crying.

MaleIdleCheckHand

Male, checking hand.

MaleIdleLookAround

Male, looking around.

MaleIdleShiftWeight

Male, shifting weight from one foot to another.

MaleIdleStretch

Male, stretching.

MaleLaugh

Male, laughing.

MaleSurprised

Male, surprised.

MaleYawn

Male, yawning.

Stand0

Gender-neutral, standing, variation 0.

Stand1

Gender-neutral, standing, variation 1.

Stand2

Gender-neutral, standing, variation 2.

Stand3

Gender-neutral, standing, variation 3.

Stand4

Gender-neutral, standing, variation 4.

Stand5

Gender-neutral, standing, variation 5.

Stand6

Gender-neutral, standing, variation 6.

Stand7

Gender-neutral, standing, variation 7.

Wave

Gender-neutral, waving.

AvatarBodyType

Defines the body type of the avatar.

Female

Female avatar.

Male

Male avatar.

AvatarBone

Defines a list of the useful bones of the avatar model.

AnkleLeft (11)

Left ankle.

AnkleRight (15)

Right ankle.

BackLower (1)

Lower back.

BackUpper (5)

Upper back.

CollarLeft (12)

Left collar.

CollarRight (16)

Right collar.

ElbowLeft (25)

Left elbow.

ElbowRight (28)

Right elbow.

FingerIndex2Left (51)

Left index finger, second joint.

FingerIndex2Right (56)

Right index finger, second joint.

FingerIndex3Left (61)

Left index finger, third joint.

FingerIndex3Right (66)

Right index finger, third joint.

FingerIndexLeft (37)

Left index finger, first joint.

FingerIndexRight (44)

Right index finger, first joint.

FingerMiddle2Left (52)

Left middle finger, second joint.

FingerMiddle2Right (57)

Right middle finger, second joint.

FingerMiddle3Left (62)

Left middle finger, third joint.

FingerMiddle3Right (67)

Right middle finger, third joint.

FingerMiddleLeft (38)

Left middle finger, first joint.

FingerMiddleRight (45)

Right middle finger, first joint.

FingerRing2Left (53)

Left ring finger, second joint.

FingerRing2Right (58)

Right ring finger, second joint.

FingerRing3Left (63)

Left ring finger, third joint.

FingerRing3Right (68)

Right ring finger, third joint.

FingerRingLeft (39)

Left ring finger, first joint.

FingerRingRight (46)

Right ring finger, first joint.

FingerSmall2Left (54)

Left pinky finger, second joint.

FingerSmall2Right (59)

Right pinky finger, second joint.

FingerSmall3Left (64)

Left pinky finger, third joint.

FingerSmall3Right (69)

Right pinky finger, third joint.

FingerSmallLeft (40)

Left pinky finger, first joint.

FingerSmallRight (47)

Right pinky finger, second joint.

FingerThumb2Left (55)

Left thumb, second joint.

FingerThumb2Right (60)

Right thumb, second joint.

FingerThumb3Left (65)

Left thumb, third joint.

FingerThumb3Right (70)

Right thumb, third joint.

FingerThumbLeft (43)

Left thumb, first joint.

FingerThumbRight (50)

Right thumb, first joint.

Head (19)

Head.

HipLeft (2)

Left hip.

HipRight (3)

Right hip.

KneeLeft (6)

Left knee.

KneeRight (8)

Right knee.

Neck (14)

Neck.

PropLeft (41)

A separate object held in the left hand.

PropRight (48)

A separate object held in the right hand.

Root (0)

Root bone of the avatar skeleton.

ShoulderLeft (20)

Left shoulder.

ShoulderRight (22)

Right shoulder.

SpecialLeft (42)

A special bone located near the left hand of the avatar model.

SpecialRight (49)

A special bone located near the right hand of the avatar model.

ToeLeft (21)

Left toe.

ToeRight (23)

Right toe.

WristLeft (33)

Left wrist.

WristRight (36)

Right wrist.

AvatarEye

Defines the standard animation textures for an avatar’s eyes.

Angry

Angry eye position.

Blink

Blinking eye position.

Confused

Confused eye position.

Happy

Happy eye position.

Laughing

Laughing eye position.

LookDown

Looking down eye position.

LookLeft

Looking left position.

LookRight

Looking right eye position.

LookUp

Looking up eye position.

Neutral

Neutral eye position.

Sad

Sad eye position.

Shocked

Shocked eye position.

Sleeping

Sleeping eye position.

Yawning

Yawning eye position.

AvatarEyebrow

Defines the standard animation textures for an avatar’s eyebrows.

Angry

Angry eyebrow position.

Confused

Confused eyebrow position.

Neutral

Neutral eyebrow position.

Raised

Raised eyebrow position.

Sad

Sad eyebrow position.

AvatarMouth

Defines the standard animation textures for an avatar’s mouth.

Angry

Angry mouth position.

Confused

Confused mouth position.

Happy

Happy mouth position.

Laughing

Laughing mouth position.

Neutral

Neutral mouth position.

PhoneticAi

Phonetic “ai” mouth position (for lip sync).

PhoneticDth

Phonetic “dth” mouth position (for lip sync).

PhoneticEe

Phonetic “ee” mouth position (for lip sync).

PhoneticFv

Phonetic “fv” mouth position (for lip sync).

PhoneticL

Phonetic “l” mouth position (for lip sync).

PhoneticO

Phonetic “o” mouth position (for lip sync).

PhoneticW

Phonetic “w” mouth position (for lip sync).

Sad

Sad mouth position.

Shocked

Shocked mouth position.

AvatarRendererState

Indicates avatar state.

Loading (0)

The avatar is still loading required assets.

Ready (1)

Loading is complete.

Unavailable (2)

The avatar is unavailable.

ControllerSensitivity

Indicates how sensitive this gamer prefers controller input to be.

High

Highly sensitive controller input is preferred.

Low

Below-average sensitivity is preferred.

Medium

Average controller sensitivity is preferred.

GameDifficulty

Indicates how difficult this gamer likes things to be.

Easy

Below-average difficulty.

Hard

Above-average difficulty.

Normal

Average difficulty.

GamerPresenceMode

Settings defining the status string that will appear when you view a friend through the Xbox Live Guide or on Xbox.com. Use the PresenceMode property to set this option.

ArcadeMode

Displays the Arcade Mode status string.

AtMenu

Displays the At Menu status string.

BattlingBoss

Displays the Battling Boss status string.

CampaignMode

Displays the Campaign Mode status string.

ChallengeMode

Displays the Challenge Mode status string.

ConfiguringSettings

Displays the Configuring Settings status string.

CoOpLevel

Displays the Co-Op: Level status string. Includes a numeric value specified with PresenceValue.

CoOpStage

Displays the Co-Op: Stage status string. Includes a numeric value specified with PresenceValue.

CornflowerBlue

Displays the Cornflower Blue status string.

CustomizingPlayer

Displays the Customizing Player status string.

DifficultyEasy

Displays the Difficulty: Easy status string.

DifficultyExtreme

Displays the Difficulty: Extreme status string.

DifficultyHard

Displays the Difficulty: Hard status string.

DifficultyMedium

Displays the Difficulty: Medium status string.

EditingLevel

Displays the Editing Level status string.

ExplorationMode

Displays the Exploration Mode status string.

FoundSecret

Displays the Found Secret status string.

FreePlay

Displays the Free Play status string.

GameOver

Displays the Game Over status string.

InCombat

Displays the In Combat status string.

InGameStore

Displays the In Game Store status string.

Level

Displays the Level status string. Includes a numeric value specified with PresenceValue.

LocalCoOp

Displays the Local Co-Op status string.

LocalVersus

Displays the Local Versus status string.

LookingForGames

Displays the Looking For Games status string.

Losing

Displays the Losing status string.

Multiplayer

Displays the Multiplayer status string.

NearlyFinished

Displays the Nearly Finished status string.

None

Displays the No Presence String Displayed status string.

OnARoll

Displays the On a Roll status string.

OnlineCoOp

Displays the Online Co-Op status string.

OnlineVersus

Displays the Online Versus status string.

Outnumbered

Displays the Outnumbered status string.

Paused

Displays the Paused status string.

PlayingMinigame

Displays the Playing Minigame status string.

PlayingWithFriends

Displays the Playing With Friends status string.

PracticeMode

Displays the Practice Mode status string.

PuzzleMode

Displays the Puzzle Mode status string.

ScenarioMode

Displays the Scenario Mode status string.

Score

Displays the Score status string. Includes a numeric value specified with PresenceValue.

ScoreIsTied

Displays the Score is Tied status string.

SettingUpMatch

Displays the Setting Up Match status string.

SinglePlayer

Displays the Single Player status string.

Stage

Displays the Stage status string. Includes a numeric value specified with PresenceValue.

StartingGame

Displays the Starting Game status string.

StoryMode

Displays the Story Mode status string.

StuckOnAHardBit

Displays the Stuck on a Hard Bit status string.

SurvivalMode

Displays the Survival Mode status string.

TimeAttack

Displays the Time Attack status string.

TryingForRecord

Displays the Trying For Record status string.

TutorialMode

Displays the Tutorial Mode status string.

VersusComputer

Displays the Versus Computer status string.

VersusScore

Displays the Versus: Score status string. Includes a numeric value specified with PresenceValue.

WaitingForPlayers

Displays the Waiting For Players status string.

WaitingInLobby

Displays the Waiting In Lobby status string.

WastingTime

Displays the Wasting Time status string.

WatchingCredits

Displays the Watching Credits status string.

WatchingCutscene

Displays the Watching Cutscene status string.

Winning

Displays the Winning status string.

WonTheGame

Displays the Won the Game status string.

GamerPrivilegeSetting

Describes the conditions in which a privilege is available.

Blocked

This privilege is not available for the current gamer profile.

Everyone

This privilege is available for the current gamer profile.

FriendsOnly

This privilege is only available for friends of the current gamer profile. Use the IsFriend method to check which gamers are friends.

GamerZone

The style of social gaming preferred by this Xbox Live member.

Family

Family-friendly gameplay.

Pro

Competitive gameplay.

Recreation

Non-competitive gameplay.

Underground

Alternative approach to gameplay.

Unknown

Unknown.

LeaderboardKey

Values used with LeaderboardIdentity.Create to select which leaderboard to access.

BestScoreLifeTime

Best lifetime score for this player and his or her Xbox Live friends.

BestScoreRecent

Best recent scores for this player and his or her Xbox Live friends.

BestTimeLifeTime

Best lifetime times for this player and his or her Xbox Live friends.

BestTimeRecent

Best recent times for this player and his or her Xbox Live friends.

LeaderboardOutcome

Values used to provide an outcome for a player’s leaderboard entry.

Loss

Player lost the match.

None

No result reported.

Tie

Match resulted in a tie; no player won.

Win

Player won the match.

MessageBoxIcon

Defines the different icons for a message box.

Alert

Displays the Alert icon.

Error

Displays the Error icon.

None

No icon is displayed.

Warning

Displays the Warning icon.

NotificationPosition

Determines where notifications appear on the screen.

BottomCenter

Positions the message box at the bottom of the screen and centered.

BottomLeft

Positions the message box at the bottom-left of the screen.

BottomRight

Positions the message box at the bottom-right of the screen.

Center

Positions the message box at the center of the screen.

CenterLeft

Positions the message box at the center of the screen and left-aligned.

CenterRight

Positions the message box at the center of the screen and right-aligned.

TopCenter

Positions the message box at the top of the screen and centered.

TopLeft

Positions the message box at the top-left of the screen.

TopRight

Positions the message box at the top-right of the screen.

RacingCameraAngle

Indicates which camera angle this gamer prefers to use in racing games.

Back

Traditional third-person camera view from behind the car.

Front

Camera view from in front of the car. The car itself is not visible.

Inside

Camera view from inside the car, looking through the windscreen.

GamerProfile Demo Program

To demonstrate the GamerServices namespace, I’ve prepared the following sample program, called GamerProfile Demo, to print some information on the screen about the currently logged-in profile. You will need to run this example on your Xbox 360, as it will not display anything under Windows (where no gamer profile exists). You do not need to have an active Xbox Live membership for this to work, but some of the information is only useful for an active account. Figure 6.1 shows the program running on an Xbox 360 with my gamer profile displayed.

The GamerProfile Demo displays information about your Xbox Live gamer profile, but it only runs on an Xbox 360.

Figure 6.1. The GamerProfile Demo displays information about your Xbox Live gamer profile, but it only runs on an Xbox 360.

The key to accessing the GamerServices class is to add a new GamerServicesComponent to the public Components collection, usually in the constructor of the Game class:

Components.Add(new GamerServicesComponent(this));

With the component added and running, you can access the currently signed-in gamer profiles—yes, that includes co-players currently using the Xbox. The following code iterates through the currently signed-in profiles to retrieve the name of each one. (Note: Normally, only one profile will be active at a time—your own profile.)

foreach (SignedInGamer gamer in SignedInGamer.SignedInGamers)
{
}

To grab just the default profile, you can just look at PlayerIndex.One:

if (Gamer.SignedInGamers[PlayerIndex.One] != null)
{
}

To keep the profile information up to date, we need to add this line to the Update() function:

GamerServicesDispatcher.Update();

Based on the reference information covered in this chapter and the SignedInGamer class, the code in Listing 6.1 should provide some pointers into the type of data available from the gamer profile.

Example 6.1. Data in the Gamer Profile

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace GamerServices_Demo
{
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    SpriteFont font;
    GamerProfile profile;
    SignedInGamer gamer;
    string labels1 = "", labels2 = "";
    string values1 = "", values2 = "";
    Texture2D picture;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        Components.Add(new GamerServicesComponent(this));
    }

    protected override void Initialize()
    {
        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        font = Content.Load<SpriteFont>("font1");
    }
    protected override void UnloadContent() { }

    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back ==
            ButtonState.Pressed)
            this.Exit();
        if (gamer == null)
        {
            if (Gamer.SignedInGamers[PlayerIndex.One] != null)
            {
                gamer = Gamer.SignedInGamers[PlayerIndex.One];
                profile = gamer.GetProfile();
            }
        }
        if (gamer != null)
        {
            if (picture == null)
            {
                picture = Texture2D.FromStream(this.GraphicsDevice,
                    profile.GetGamerPicture());
            }
            labels1 = "Gamertag: 
" +
                "Signed on: 
" +
                "Gamer score: 
" +
                "Gamer zone: 
" +
                "Motto: 
" +
                "Region: 
" +
                "Reputation: 
" +
                "Titles played: 
" +
                "Achievements: 
" +
                "Gamer picture: ";
            values1 = gamer.Gamertag + "
" +
                gamer.IsSignedInToLive.ToString() + "
" +
                profile.GamerScore.ToString() + "
" +
                profile.GamerZone.ToString() + "
" +
                profile.Motto + "
" +
                profile.Region.Name + "
" +
                profile.Reputation.ToString() + "
" +
                profile.TitlesPlayed.ToString() + "
" +
                profile.TotalAchievements.ToString() + "
";
            labels2 = "Privileges 
" +
                "  AllowCommunication: 
" +
                "  AllowOnlineSessions: 
" +
                "  AllowProfileViewing: 
" +
                "  AllowPurchaseContent: 
" +
                "  AllowTradeContent: 
" +
                "  AllowUserCreatedContent: 

" +
                "GameDefaults 
" +
                "  AccelerateWithButtons: 
" +
                "  AutoAim: 
" +
                "  AutoCenter: 
" +
                "  BrakeWithButtons: 
" +
                "  ControllerSensitivity: 
" +
                "  GameDifficulty: 
" +
                "  InvertYAxis: 
" +
                "  ManualTransmission: 
" +
                "  MoveWithRightThumbStick: 
" +
                "  RacingCameraAngle: ";
            values2 = "
" +
            gamer.Privileges.AllowCommunication.ToString() + "
" +
            gamer.Privileges.AllowOnlineSessions.ToString() + "
" +
            gamer.Privileges.AllowProfileViewing.ToString() + "
" +
            gamer.Privileges.AllowPurchaseContent.ToString() + "
" +
            gamer.Privileges.AllowTradeContent.ToString() + "
" +
            gamer.Privileges.AllowUserCreatedContent.ToString() + "
" +
            "

" +
            gamer.GameDefaults.AccelerateWithButtons.ToString() + "
" +
            gamer.GameDefaults.AutoAim.ToString() + "
" +
            gamer.GameDefaults.AutoCenter.ToString() + "
" +
            gamer.GameDefaults.BrakeWithButtons.ToString() + "
" +
            gamer.GameDefaults.ControllerSensitivity.ToString() + "
" +
            gamer.GameDefaults.GameDifficulty.ToString() + "
" +
            gamer.GameDefaults.InvertYAxis.ToString() + "
" +
            gamer.GameDefaults.ManualTransmission.ToString() + "
" +
            gamer.GameDefaults.MoveWithRightThumbStick.ToString() + "
" +
            gamer.GameDefaults.RacingCameraAngle.ToString();
        }
        GamerServicesDispatcher.Update();
        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
       GraphicsDevice.Clear(Color.CornflowerBlue);
       spriteBatch.Begin();

       if (Environment.OSVersion.Platform != PlatformID.Xbox)
       {
           labels1 = "This demo only runs on an Xbox 360";
           values1 = "";
           labels2 = "";
           values2 = "";

        }

        //print first column
        print(10, 10, labels1, Color.White);
        print(150, 10, values1, Color.White);

        //print second column
        print(340, 10, labels2, Color.White);
        print(610, 10, values2, Color.White);

        //draw gamer picture
        if (picture != null)
        {
            Vector2 size = font.MeasureString(labels1);
            Vector2 pos = new Vector2(150, size.Y);
            spriteBatch.Draw(picture, pos, Color.White);
        }

        spriteBatch.End();
        base.Draw(gameTime);
    }

    void print(int x, int y, string text, Color color)
    {
        spriteBatch.DrawString(font, text,
            new Vector2((float)x, (float)y), color);
    }
}
}

Summary

The GamerServices namespace contains a lot of amazing information about the gamer profile, including the gamer picture, gamer tag, friends list, and even the 3D avatar animations. We only scratched the surface of what’s available in GamerServices with the sample program, but it should give you an idea about how to use this information in your own projects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.14.63