1 Session 16.2 Network Games and State Chapter 16.2: Network Games and State 2 Session Overview We now know the fundamentals of network communication Now we are going to see how XNA uses the underlying network to provide network game play We are going to discover the ways in which you can use XNA to create connected games and how to create a state machine to manage a network game We are also going to find out how C# programs can bind to events caused by the network Chapter 16.2: Network Games and State 3 Xbox Live “Xbox Live” is the name for the multiplayer gaming interface which provides network game play On the Windows PC it is know as “Games for Windows – Live” Paid up members have a unique gamertag that gives them an identity (and an avatar) on the network Xbox Live contains Xbox Live Arcade where members can buy and download games, including some created using XNA Chapter 16.2: Network Games and State 4 XNA and Xbox Live XNA games can use Xbox Live in exactly the same way as other Xbox games XNA games that you write can be uploaded as “Indie Games” for purchase and download from the Xbox Live Arcade This is a great way to get started as a game developer You have to pay $99 to become a “Premium” member of the XNA Creators Club to do this Chapter 16.2: Network Games and State XNA and Zune Networked Game Play The Zune music player will run XNA games It also has WIFI networking built in XNA games can use this to create network game play between Zune devices The network connections that are set up and managed during the game are exactly the same way for a Zune as any other XNA device This makes it very easy to create portable, networked game play 5 Chapter 16.2: Network Games and State 6 Connected XNA Games XNA provides a set of classes and types that are used to set up network games Our network games will use these classes to initiate network connections, set up games, and then pass game information between the systems in the game The type of game we are going to use lets Xbox and Windows PC gamers play against each other However, Zunes can only link to other Zunes Chapter 16.2: Network Games and State 7 “System Link” XNA Games While it is possible to create fully featured Xbox Live games using XNA we are going to start with a simpler version A “System Link” game lets machines on the same local area network connect for game play These network connections are simple to set up and do not require Xbox Live membership to work System Link is the only form of network game play that is supported by the Zune device Chapter 16.2: Network Games and State 8 Gamer Profiles and Gamer Tags Xbox users can create user profiles on their consoles to store their game play achievements These profiles can be linked to the Xbox Live Gamer Tags On the Windows PC you can create Gamer Profiles that work in the same way A “System Link” game uses these profiles to locate players connected to the same local area network Fully-featured Xbox Live games use Xbox Live servers to locate players Chapter 16.2: Network Games and State 9 Setting Up an XNA Networked Game Before you can create a networked game you need to be signed in on your system You use a particular Gamer Profile to sign in This sign-in provides you with an identity on the network that others can find and invite to take part in games It is the profile that is addressed, not the computer or console itself Chapter 16.2: Network Games and State 10 Managing Game Profiles in XNA The Xbox 360 provides a “Guide” interface that players can use to create and manage their gamer profile You press the X in the middle of the gamepad to open up the Guide and interact with it Windows PC users have the same facility in their XNA games They can start the guide by pressing the Home key on the keyboard Chapter 16.2: Network Games and State 11 Loading the GamerServices Component public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; this.Components.Add(new GamerServicesComponent(this)); } To get the Guide to work we have to load the GamerServicesComponent to a game program We can do this in the constructor for the game Once this component is present, the Home key can be used to start the Guide on a Windows PC Chapter 16.2: Network Games and State 12 1. Guide Demo If you add the GamerServicesComponent to the game you can use the Home key to open up Guide on a Windows PC the Chapter 16.2: Network Games and State 13 Ensuring a Gamer Is Signed In if (Gamer.SignedInGamers.Count == 0) { if (Guide.IsVisible == false) { Guide.ShowSignIn(1, false); } } XNA provides a type called Gamer that is used to manage network gaming This provides a property called SignedInGamers that contains a collection of all the gamers signed in If this is empty there is nobody signed in Chapter 16.2: Network Games and State 14 Ensuring a Gamer Is Signed In if (Gamer.SignedInGamers.Count == 0) { if (Guide.IsVisible == false) { Guide.ShowSignIn(1, false); } } The Guide class lets a program control the guide An XNA game can request that the Guide be displayed during a game It has a property IsVisible that is tested to make sure that the guide is not displayed twice Chapter 16.2: Network Games and State 15 Ensuring a Gamer Is Signed In if (Gamer.SignedInGamers.Count == 0) { if (Guide.IsVisible == false) { Guide.ShowSignIn(1, false); } } The ShowSignIn method displays the sign in screen and has two parameters: The number of players to sign in on the device (which must be one for the Windows PC) Whether to restrict the sign in to only allow online players (those with Xbox Live accounts) Chapter 16.2: Network Games and State 16 Gamer Sign In By using the Gamer.SignedInGamers type and the Guide, an XNA game can ensure that a gamer is signed in The gamer can then take part in network games Xbox and Windows PC players can see each other and take part in games together The Zune doesn’t need a gamer to sign in, a gamer on a Zune has a profile with the name of the Zune device Chapter 16.2: Network Games and State 17 Setting Up a Network Game Lobby A lobby is managed by one system on the network The system “proposes” a particular game and waits for players to join the lobby and start game play XNA provides features that manage a game lobby Chapter 16.2: Network Games and State Bread and Cheese Pong We are going to create a simple two-player game “Bread and Cheese Pong” The game will need a lobby where players can gather The lobby will be very small, but can be expanded to handle larger numbers if required 18 Chapter 16.2: Network Games and State 19 Network Games and State public enum GameState { titleScreen, NotSignedIn, SelectingRole, WaitingAsHost, WaitingAsPlayer, PlayingAsPlayer, PlayingAsHost } A network game is a state machine with additional states which include the lobby state These are all the states our game will occupy Chapter 16.2: Network Games and State Pong States This is a state diagram It shows how a game moves between states It also shows the screens and the events that cause the state changes 20 Chapter 16.2: Network Games and State titleScreen State Update Action case GameState.titleScreen: if (gamePad1.Buttons.A == ButtonState.Pressed) { state = GameState.NotSignedIn; } break; We can use a switch construction to select the actions performed during Update If the game is in the titleScreen state it must test for button A on the gamepad If this is pressed the game state will change to NotSignedIn 21 Chapter 16.2: Network Games and State Special Behavior for the Zune case GameState.NotSignedIn: #if ZUNE state = GameState.SelectingRole; #else // code to test players and display guide #endif The Zune version of XNA does not include Guide support – attempts to use the Guide stop the program from compiling We can use conditional compilation to skip code that won’t work on the Zune 22 Chapter 16.2: Network Games and State Hosting a Game if (gamePad1.DPad.Left == ButtonState.Pressed) { // Selected Host role // Create the session session = NetworkSession.Create( NetworkSessionType.SystemLink, 1, // only 1 local gamer 2 // no more than 2 players ); A player can decide to host a game They will have to wait for players to join the game before the game can start A host starts by making a network session 23 Chapter 16.2: Network Games and State 24 The NetworkSession Class // Game World NetworkSession session = null; The NetworkSession class provides methods and properties which manage a network game The host creates an instance of this class and uses it to set up the game, manage the players in the game, and send messages to them The class also generates events that we can use to trigger actions in our game Chapter 16.2: Network Games and State 25 Network Session Type session = NetworkSession.Create( NetworkSessionType.SystemLink, 1, // only 1 local gamer 2 // no more than 2 players ); There are a number of different types of network games Some of them involve the use of Xbox Live The SystemLink type of game works on a local area network It is the only kind of game supported by the Zune Chapter 16.2: Network Games and State Number of Local Players session = NetworkSession.Create( NetworkSessionType.SystemLink, 1, // only 1 local gamer 2 // no more than 2 players ); An Xbox can support up to 4 local gamers for split screen multi-player game play The Windows PC can only support one player on a system This value must be set to 1 to indicate this 26 Chapter 16.2: Network Games and State Number of Players session = NetworkSession.Create( NetworkSessionType.SystemLink, 1, // only 1 local gamer 2 // no more than 2 players ); This is where you set the maximum number of players the session will accept We only need two players for Pong If you wanted to allow more players you would increase this number 27 Chapter 16.2: Network Games and State Lobbies and Events The XNA program creating the session does not want to have to wait around for people to join the game XNA wants to call Update and Draw 60 times a second to keep the game running We therefore need some way that the NetworkSession value can tell the game when someone turns up to play the game This is done using C# events 28 Chapter 16.2: Network Games and State Events in Programs We use events all the time: You don’t wait in the garage for your car to be mended, you give the garage your number and say “Call me when it is fixed” Events let programs do the same thing They let us give a NetworkSession object a reference to a method and say “Call this method when someone joins the game we are hosting” Events are used in Windows to implement screen button presses, mouse clicks, and timers 29 Chapter 16.2: Network Games and State 30 Detecting Gamer Joined Events session.GamerJoined += new EventHandler<GamerJoinedEventArgs>(hostSession_GamerJoined); A session provides a GamerJoined event We can add new EventHandler delegates to this event by using the += operator A delegate is a reference to a method in an object In the code above, a new EventHandler is created referring to the method hostSession_GamerJoined When the event occurs the method is called Chapter 16.2: Network Games and State 31 Creating a Delegate Instance session.GamerJoined += new EventHandler<GamerJoinedEventArgs>(hostSession_GamerJoined); The type EventHandler is a delegate type It creates an object that contains a reference to a method in an object The constructor of the EventHandler is given the name of the method the delegate must refer to The EventHandler that is created is added to the list of delegates to be called when the event occurs Chapter 16.2: Network Games and State The Bottom Line with Delegates We want a way that the NetworkSession value can alert our game to a player entering the lobby and joining the game A delegate does exactly this for us We connect the delegate (a reference to our method) to the GamerJoined event that the NetworkSession object provides When a gamer joins the game, the method hostSession_GamerJoined will be called 32 Chapter 16.2: Network Games and State 33 The hostSession_GamerJoined Method void hostSession_GamerJoined(object sender, GamerJoinedEventArgs e) { if (session.RemoteGamers.Count == 1) { StartGame (); state = GameState.PlayingAsHost; } } This method in our game is called when a gamer joins the game It checks to see if we have 1 remote gamer If we do it calls StartGame to start the game and changes the game state to PlayingAsHost Chapter 16.2: Network Games and State 34 Hosting the Lobby We now know what happens when a system hosts a game of “Bread and Cheese Pong”: It makes a new NetworkSession object, referred to by a game world variable called session It uses a delegate to connect a method to the GamerJoined event provided by the session variable When a gamer joins the game the method is called It starts the game running There is also an event, GamerLeft, that is fired if a gamer leaves the lobby Chapter 16.2: Network Games and State 35 Waiting as a Player if (gamePad1.DPad.Right == ButtonState.Pressed) { // Selected Player role state = GameState.WaitingAsPlayer; } If a player presses Right they will be a player in the game, and must look for hosted games to join The state of the game changes to reflect this Their game must now try to find any hosted games and join them to start the game running Chapter 16.2: Network Games and State 36 Finding Games AvailableNetworkSessionCollection sessions = NetworkSession.Find(NetworkSessionType.SystemLink, 1, null); if (sessions.Count > 0) { AvailableNetworkSession mySession = sessions[0]; session = NetworkSession.Join(mySession); session.GamerLeft += new EventHandler<GamerLeftEventArgs>(playerSession _GamerLeft); StartGame(); state = GameState.PlayingAsPlayer; } This code looks for available network sessions and joins the first one that it finds You could make it more discerning Chapter 16.2: Network Games and State 37 Using the Find Method AvailableNetworkSessionCollection sessions = NetworkSession.Find(NetworkSessionType.SystemLink, 1, null); if (sessions.Count > 0) { AvailableNetworkSession mySession = sessions[0]; session = NetworkSession.Join(mySession); session.GamerLeft += new EventHandler<GamerLeftEventArgs>(playerSession _GamerLeft); StartGame(); state = GameState.PlayingAsPlayer; } The Find method delivers a list of games that match the criteria specified SystemLink games with 1 local player Chapter 16.2: Network Games and State 38 Joining a Session AvailableNetworkSessionCollection sessions = NetworkSession.Find(NetworkSessionType.SystemLink, 1, null); if (sessions.Count > 0) { AvailableNetworkSession mySession = sessions[0]; session = NetworkSession.Join(mySession); session.GamerLeft += new EventHandler<GamerLeftEventArgs>(playerSession _GamerLeft); StartGame(); state = GameState.PlayingAsPlayer; } If the list of sessions returned by Find is not empty we join the first one on the list This is the one with subscript 0 on the list Chapter 16.2: Network Games and State 39 Creating a Network Session AvailableNetworkSessionCollection sessions = NetworkSession.Find(NetworkSessionType.SystemLink, 1, null); if (sessions.Count > 0) { AvailableNetworkSession mySession = sessions[0]; session = NetworkSession.Join(mySession); session.GamerLeft += new EventHandler<GamerLeftEventArgs>(playerSession _GamerLeft); StartGame(); state = GameState.PlayingAsPlayer; } The Join method returns a NetworkSession that represents the game that has been joined This is the session that will be used for this game Chapter 16.2: Network Games and State 40 Detecting When the Game Ends AvailableNetworkSessionCollection sessions = NetworkSession.Find(NetworkSessionType.SystemLink, 1, null); if (sessions.Count > 0) { AvailableNetworkSession mySession = sessions[0]; session = NetworkSession.Join(mySession); session.GamerLeft += new EventHandler<GamerLeftEventArgs>(playerSession _GamerLeft); StartGame(); state = GameState.PlayingAsPlayer; } This event is fired if the host leaves the game We need to get control then so that we can abandon the game Chapter 16.2: Network Games and State 41 Starting the Player Game AvailableNetworkSessionCollection sessions = NetworkSession.Find(NetworkSessionType.SystemLink, 1, null); if (sessions.Count > 0) { AvailableNetworkSession mySession = sessions[0]; session = NetworkSession.Join(mySession); session.GamerLeft += new EventHandler<GamerLeftEventArgs>(playerSession _GamerLeft); StartGame(); state = GameState.PlayingAsPlayer; } This starts the game and sets the state to PlayingAsPlayer The game play can now begin Chapter 16.2: Network Games and State 42 Summary XNA provides a set of objects that are used to create and manage network game play A networked game has an expanded state machine that contains states required to set up the network XNA games have a lobby which is hosted by one player and which other players can find and join A C# delegate is a reference to a method in an object Delegates are used to connect program events to the code that will deal with them