microsoft visual basic game programming with directx phần 8 ppt

57 385 0
microsoft visual basic game programming with directx phần 8 ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

.NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen Hatton ISBN:1590590511 Apress © 2003 (696 pages) The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft's Visual Studio. Table of Contents .NET Game Programming with DirectX 9.0 Foreword Preface Introduction Chapter 1 - .Nettrix: GDI+ and Collision Detection Chapter 2 - .Netterpillars: Artificial Intelligence and Sprites Chapter 3 - Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+ Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay Chapter 9 - D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code Bonus Chapter Porting .Nettrix to Pocket PC Appendix A - The State of PC Gaming Appendix B - Motivations in Games Appendix C - How Do I Make Games? Appendix D - Guidelines for Developing Successful Games Index List of Figures List of Tables RegKey.Close() Catch lstServiceProviders.SelectedIndex = 0 End Try Else lstServiceProviders.SelectedIndex = 0 End If End Sub In the next section , we'll write the code for creating game sessions and joining them. Coding the Session Methods Although we are coding a single class, for the sessions there'll be specific methods executed by the host and others used by the client. We'll discuss these methods in separated sections so that we won't confuse the two. Creating and Destroying Sessions To create a session in DirectPlay, we simply call the Host method of the Peer object, passing the appropriated parameters, which enables us to receive connections from other computers. The Host method will receive two parameters: an ApplicationDescription object, which will give the game GUID and the session name, and the Address object, which points to the service provider to be used: Public Function CreateSession(strSessionName As String) As Boolean Try ' Create the application description object Dim AppDesc As New ApplicationDescription() AppDesc.GuidApplication = GameGuid AppDesc.SessionName = strSessionName ' No special flags AppDesc.Flags = 0 'Host a game on DPAddress as described by AppDesc DPPeer.Host(AppDesc, DPAddress) CreateSession = True Catch e As DirectPlayException MessageBox.Show("Error when creating a session: " & e.ErrorString & _ " - " & e.ErrorString, "clsGameServer.CreateSession") CreateSession = False End Try End Function We must follow here a rule of thumb for any program: Close what you opened. So we'll add code for the CloseConnection method, which can be called if the program wants to explicitly close the connection to other computers. Public Sub CloseConnection() DPPeer.Dispose() End Sub These two methods will be used only by the Host, and they are all we need to create and destroy game sessions. Since many games will need a configuration screen to receive the session name from the player, we can add an extra Create-Session method that receives no parameter and presents a window that will ask for .NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen Hatton ISBN:1590590511 Apress © 2003 (696 pages) The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft's Visual Studio. Table of Contents .NET Game Programming with DirectX 9.0 Foreword Preface Introduction Chapter 1 - .Nettrix: GDI+ and Collision Detection Chapter 2 - .Netterpillars: Artificial Intelligence and Sprites Chapter 3 - Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+ Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay Chapter 9 - D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code Bonus Chapter Porting .Nettrix to Pocket PC Appendix A - The State of PC Gaming Appendix B - Motivations in Games Appendix C - How Do I Make Games? Appendix D - Guidelines for Developing Successful Games Index List of Figures List of Tables the session name. The code for such an overloaded method is given in the next code section: Public Function CreateSession() As Boolean Dim WinCreateSession As frmCreateSession CreateSession = True WinCreateSession = New frmCreateSession(Me) If WinCreateSession.ShowDialog() <> DialogResult.OK Then CreateSession = False End If End Function The window that will receive the session name contains only a text box and two buttons, as shown in Figure 8-8 . Figure 8-8: Entering a session name in the Server Configuration window We'll add code in this window to receive the NetworkGame object and store the previous session name in the registry, as shown in the Service Provider window. We'll also call the CreateSession method in the NetworkGame object to effectively create the session. The full code for this window is shown in the following listing: Private objGameClient As ClsNetworkGame Public Sub New(GameClient As ClsNetworkGame) MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() objGameClient = GameClient 'Get the default session from the registry if it exists Dim RegKey As RegistryKey = _ Registry.CurrentUser.OpenSubKey(_ "Software\\Games\\NetterpillarsII") If Not (RegKey Is Nothing) Then txtSession.Text = RegKey.GetValue("DirectPlaySessionName", Nothing) RegKey.Close() End If End Sub Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click If ((txtSession.Text = Nothing) Or (txtSession.Text = "")) Then MessageBox.Show(Me, "Please enter a session name before clicking OK.", _ "No sessionname", MessageBoxButtons.OK, MessageBoxIcon.Information) Return End If ' Save the session name to the registry as a new default .NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen Hatton ISBN:1590590511 Apress © 2003 (696 pages) The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft's Visual Studio. Table of Contents .NET Game Programming with DirectX 9.0 Foreword Preface Introduction Chapter 1 - .Nettrix: GDI+ and Collision Detection Chapter 2 - .Netterpillars: Artificial Intelligence and Sprites Chapter 3 - Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+ Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay Chapter 9 - D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code Bonus Chapter Porting .Nettrix to Pocket PC Appendix A - The State of PC Gaming Appendix B - Motivations in Games Appendix C - How Do I Make Games? Appendix D - Guidelines for Developing Successful Games Index List of Figures List of Tables Dim RegKey As RegistryKey = _ Registry.CurrentUser.CreateSubKey(_ "Software\\Games\\NetterpillarsII") If Not (RegKey Is Nothing) Then RegKey.SetValue("DirectPlaySessionName", txtSession.Text) RegKey.Close() End If If objGameClient.CreateSession(txtSession.Text) Then Me.DialogResult = DialogResult.OK Else Me.DialogResult = DialogResult.Cancel End If End Sub In the next section , we'll present the code that will run on the client side used to list all sessions on a specific host. Listing Existing Sessions on a Remote Computer To connect to a session on a host involves knowing the server name and the session name and GUID we want to connect to, since all these pieces of information when used together uniquely define a session. We'll also need to get the player name as an input so we can pass it to the host when connecting. Our ChooseSessionToJoin method will be very similar to the ChooseServiceProvider one; it will only create a window that prompts for the user name and presents a list of available sessions in a given host, as presented in the next code listing: Public Function ChooseSessionToJoin() As Boolean Dim WinJoin As frmJoin ChooseSessionToJoin = True WinJoin = New frmJoin(Me) If WinJoin.ShowDialog() <> DialogResult.OK Then ChooseSessionToJoin = False End If End Function As in the ChooseServiceProvider method, we'll also pass the current object as a parameter to the window, which will be stored in a variable to be used in the window. However, as we'll see, connecting to a remote session takes a lot more effort than simply choosing a service provider. Figure 8-9 presents the window interface that will allow us to choose the session on the remote computer. Figure 8-9: Join a session window The first problem in this window arises from the transitory nature of the sessions. We can't simply list all the sessions in a host when the window loads, because while the user types his or her name or reads the available .NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen Hatton ISBN:1590590511 Apress © 2003 (696 pages) The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft's Visual Studio. Table of Contents .NET Game Programming with DirectX 9.0 Foreword Preface Introduction Chapter 1 - .Nettrix: GDI+ and Collision Detection Chapter 2 - .Netterpillars: Artificial Intelligence and Sprites Chapter 3 - Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+ Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay Chapter 9 - D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code Bonus Chapter Porting .Nettrix to Pocket PC Appendix A - The State of PC Gaming Appendix B - Motivations in Games Appendix C - How Do I Make Games? Appendix D - Guidelines for Developing Successful Games Index List of Figures List of Tables session names, the remote computer may already have closed some of them. We can work around this problem by inserting a timer in the window and including code for refreshing the list to remove items that are no longer valid, while inserting new ones. Looking back at the GameNetwork class definition, we'll see that there is already a method that will list the hosts and sessions, called EnumHosts , so we can call it in the Load event of the form and in the Tick event of the timer. The EnumHosts method of our class will use the FindHosts method of the Peer class to loop through the sessions running on a specific host. Tip The FindHosts method enumerates sessions in a host, not hosts in a network, despite its name. The FindHosts method will receive the ApplicationDescription with information about the application we are looking for, including its unique identifier, the Address that points to the service provider, and a handle that will be used to control the operation-which is asynchronous by default. The method also receives the Address of the host, which is optional, and an enumeration value. Through this value we can set some method execution directives, forcing the method to run synchronously, to not use broadcasting if it's available, and to ask for extra information if needed (for example, the host name if it's not provided). FindHosts won't produce any visible results when called; we must code another function to handle the FindHostResponse event of the Peer object, which will be called once for each session present on the remote computer. To allow our NetworkGame class to pass information to the calling application, in this case the window shown in Figure 8-9 , we'll run an event on our handler function. Let's look at all of these pieces one by one, starting with the EnumHosts method, which will set the appropriate parameters and call the FindHosts method. Private EnumHostsAsyncHandle as integer Public Sub EnumHosts() Dim desc As ApplicationDescription = New ApplicationDescription() ' Get the current game GUID from the class property desc.GuidApplication = GameGuid 'Try to enum the game hosts Try DPPeer.FindHosts(desc, Nothing, DPAddress, Nothing, Timeout.Infinite, _ 0, Timeout.Infinite, EnumHostsAsyncHandle, _ FindHostsFlags.OkToQueryForAddressing) Catch e As DirectPlayException MessageBox.Show("Error when looking for hosts: " & e.ErrorString) End Try End Sub When we call the FindHosts method, it will present a window to the user asking for the host name, because we don't provide a specific host name. There's no way of customizing this window, which is shown in Figure 8- 10 . However, we can create our own window and pass the host name as the second parameter of the FindHosts method, which is receiving Nothing in the previous code listing. .NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen Hatton ISBN:1590590511 Apress © 2003 (696 pages) The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft's Visual Studio. Table of Contents .NET Game Programming with DirectX 9.0 Foreword Preface Introduction Chapter 1 - .Nettrix: GDI+ and Collision Detection Chapter 2 - .Netterpillars: Artificial Intelligence and Sprites Chapter 3 - Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+ Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay Chapter 9 - D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code Bonus Chapter Porting .Nettrix to Pocket PC Appendix A - The State of PC Gaming Appendix B - Motivations in Games Appendix C - How Do I Make Games? Appendix D - Guidelines for Developing Successful Games Index List of Figures List of Tables Figure 8-10: The FindHosts method asking for the host name In the following code sample, we see the event's definition (as shown in the class definition, earlier in this chapter) and the code for the EnumResponseMsg method. This method is the handler of the FindHostResponse event, which will be triggered by DirectPlay when we call FindHosts . ' Event used to enumerate hosts to connect Public Event EnumHost(AppDesc As ApplicationDescription, _ sender As Address, device As Address) Sub EnumResponseMsg(sender As Object, dpMsg As FindHostResponseEventArgs) _ Handles DPPeer.FindHostResponse ' Generate an event to RaiseEvent EnumHost(dpMsg.Message.ApplicationDescription, _ dpMsg.Message.AddressSender, dpMsg.Message.AddressDevice) End Sub With these two methods, we'll be able to call EnumHosts from the window and receive events with the session data so we can update our list box; but three extra methods are needed to allow proper control of the asynchronous session listing. We'll need one method to allow the main program to cancel the enumeration if it needs to, and another method to receive the result of the asynchronous operation when it's completed. Finally, we must explicitly cancel the asynchronous operation if the NetworkGame object has been destroyed to avoid errors that can arise if DirectPlay sends an event and the calling object is no longer valid. The code for these methods is shown in the next listing: Public Sub EnumHostsCancel() If (EnumHostsAsyncHandle <> 0) Then DPPeer.CancelAsyncOperation(EnumHostsAsyncHandle) End If End Sub Private Sub AsyncComplete(sender As Object, _ dpMsg As AsyncOperationCompleteEventArgs) Handles _ DPPeer.AsyncOperationComplete If (dpMsg.Message.AsyncOperationHandle = EnumHostsAsyncHandle) Then EnumHostsAsyncHandle = 0 End If End Sub Protected Overrides Sub Finalize() MyBase.Finalize() If (EnumHostsAsyncHandle <> 0) Then DPPeer.CancelAsyncOperation(EnumHostsAsyncHandle) End If End Sub .NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen Hatton ISBN:1590590511 Apress © 2003 (696 pages) The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft's Visual Studio. Table of Contents .NET Game Programming with DirectX 9.0 Foreword Preface Introduction Chapter 1 - .Nettrix: GDI+ and Collision Detection Chapter 2 - .Netterpillars: Artificial Intelligence and Sprites Chapter 3 - Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+ Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay Chapter 9 - D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code Bonus Chapter Porting .Nettrix to Pocket PC Appendix A - The State of PC Gaming Appendix B - Motivations in Games Appendix C - How Do I Make Games? Appendix D - Guidelines for Developing Successful Games Index List of Figures List of Tables With all these methods in place, we can now go to the window we created to list the sessions and start adding code to the Load event and the Tick event of the timer, and coding the handler of the NetworkGame object that will update the list box in the window. The simplest code that will allow us to list the sessions as shown in Figure 8-9 is given in the following code sample: Sub form_Load(sender As Object, e As EventArgs) Handles MyBase.Load 'Enum the game hosts lstSession.Items.Clear objGameClient.EnumHosts() End Sub Sub ListHosts(AppDesc As ApplicationDescription, _ sender As Address, device As Address) Handles objGameClient.EnumHost lstSession.Items.Add(SessionInfo) End Sub Sub tmrUpdateConnections_Tick(sender As System.Object, _ e As System.EventArgs) Handles tmrUpdateConnections.Tick 'Enum the game hosts lstSession.Items.Clear objGameClient.EnumHosts() End Sub Although very simple, this code isn't effective, since the list box is cleared on each tick of the timer, creating a "flashing" effect for the player; the items are removed and included again at every timer cycle, making it impossible for the player to select a specific session from the list. We need to store some extra information in the list box to determine when a specific item is included, so that it's only removed after a specific time-out (say, 2 seconds). The main problem with this approach is that we are storing only the session names in the list box, whereas we'll need the host address and the device address (received as parameters by the ListHosts method), in addition to the inclusion time value, to allow us to connect to a remote session. We'll need to improve our routines to store all the information we need in the list box. We don't need to create an object for this-we can use a simple structure, as defined in the next code sample: Private Structure stSessionInfo Public LastEnumTime As Integer Public AppDesc As ApplicationDescription Public host As Address Public device As Address Public Overrides Function ToString() As String If AppDesc.MaxPlayers > 0 Then Return AppDesc.SessionName & " (Players: " & _ AppDesc.CurrentPlayers & "/" & AppDesc.MaxPlayers & ")" Else Return AppDesc.SessionName & " (Players: " & _ AppDesc.CurrentPlayers & ")" End If End Function 'ToString End Structure .NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen Hatton ISBN:1590590511 Apress © 2003 (696 pages) The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft's Visual Studio. Table of Contents .NET Game Programming with DirectX 9.0 Foreword Preface Introduction Chapter 1 - .Nettrix: GDI+ and Collision Detection Chapter 2 - .Netterpillars: Artificial Intelligence and Sprites Chapter 3 - Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+ Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay Chapter 9 - D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code Bonus Chapter Porting .Nettrix to Pocket PC Appendix A - The State of PC Gaming Appendix B - Motivations in Games Appendix C - How Do I Make Games? Appendix D - Guidelines for Developing Successful Games Index List of Figures List of Tables In this structure, the ToString method is mandatory, or we'll get an error when trying to include the object in the list box. The list box always looks for this conversion method to find out what to show the user. The new version of the ListHosts method that will store all values in the list box is shown in the next listing: Sub ListHosts(AppDesc As ApplicationDescription, _ host As Address, device As Address) Handles objGameClient.EnumHost Dim Found As Boolean = False Dim i As Integer Dim SessionInfo As stSessionInfo = New stSessionInfo() With SessionInfo .AppDesc = AppDesc .device = device .host = host .LastEnumTime = Environment.TickCount End With 'Check the list of items first and see if this one already exists For i = 0 To lstSession.Items.Count - 1 If SessionInfo.AppDesc.GuidInstance.Equals( _ lstSession.Items(i).AppDesc.GuidInstance) Then lstSession.Items(i) = SessionInfo Found = True End If Next 'If the item is not on the list, add it If Not Found Then lstSession.Items.Add(SessionInfo) End If End Sub In the previous code sample, we checked for repeated items before including any values in the list, since now we won't clear the items from the list every time we want to enumerate the sessions. The Tick event of the timer will also need to be updated to check for timedout items and remove them from the list, as we can see in the following code listing: Sub tmrUpdateConnections_Tick(sender As System.Object, _ e As System.EventArgs) Handles tmrUpdateConnections.Tick Dim i As Integer ' Remove any timed-out sessions For i = 0 To lstSession.Items.Count - 1 'Check to see if this session has expired (every 2 seconds) If (Environment.TickCount - lstSession.Items(i).LastEnumTime > 2000) Then lstSession.Items.RemoveAt(i) Exit For End If Next 'Enum the game hosts objGameClient.EnumHosts() End Sub .NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen Hatton ISBN:1590590511 Apress © 2003 (696 pages) The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft's Visual Studio. Table of Contents .NET Game Programming with DirectX 9.0 Foreword Preface Introduction Chapter 1 - .Nettrix: GDI+ and Collision Detection Chapter 2 - .Netterpillars: Artificial Intelligence and Sprites Chapter 3 - Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+ Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay Chapter 9 - D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code Bonus Chapter Porting .Nettrix to Pocket PC Appendix A - The State of PC Gaming Appendix B - Motivations in Games Appendix C - How Do I Make Games? Appendix D - Guidelines for Developing Successful Games Index List of Figures List of Tables Since we are now removing only the timed-out items and including only extra sessions in the list, we can set the timer to do updates at shorter time intervals- for example, every 500 ms (although we should keep it at every second or two if we are using the Internet). In the next section , we'll see how to connect to a remote session using the data collected when we listed all sessions on a host. Connecting to a Remote Session Once we have the remote host address, the address of the device, and the ApplicationDescription that uniquely defines a remote session, we can connect to the host by calling the Connect method of the Peer object, as we can see in the next code snippet: Public Function Connect(AppDesc As ApplicationDescription, _ host As Address, device As Address) As Boolean DPPeer.Connect(AppDesc, host, device, Nothing, _ ConnectFlags.OkToQueryForAddressing) End Function The Peer object will trigger an event to the application saying that the connection has been completed. Since our NetworkGame class is encapsulating the features from DirectPlay, we'll also trigger an event to the main program so that it will know that the connection has been completed. Besides the connection result code, we'll send a Boolean value indicating the connection result (true for connected, false for error) so the application can easily check if it's connected or not. The following code sample presents the event definition and the handler for the ConnectComplete event of the Peer object: Public Event ConnectionResult(connected As Boolean, errcode As ResultCode) Private Sub ConnectResult(sender As Object, _ dpMsg As ConnectCompleteEventArgs) Handles DPPeer.ConnectComplete If (dpMsg.Message.ResultCode = 0) Then RaiseEvent ConnectionResult(True, dpMsg.Message.ResultCode) Else RaiseEvent ConnectionResult(False, dpMsg.Message.ResultCode) End If End Sub The last thing we must do to complete the coding that deals with connections is to write the event handler for the SessionTerminated event of the Peer object so we can inform the main application that the session has been terminated, which usually happens when we face a network problem or the remote computer has disconnected. Public Event SessionTerminated(msg As TerminateSessionMessage) Private Sub SessionFinished(sender As Object, _ dpMsg As SessionTerminatedEventArgs) Handles DPPeer.SessionTerminated ' Well, this session is being terminated, let the user know RaiseEvent SessionTerminated(dpMsg.Message) End Sub In the next section , we'll see the code that will enable us to access the features in DirectPlay to manage players. .NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen Hatton ISBN:1590590511 Apress © 2003 (696 pages) The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft's Visual Studio. Table of Contents .NET Game Programming with DirectX 9.0 Foreword Preface Introduction Chapter 1 - .Nettrix: GDI+ and Collision Detection Chapter 2 - .Netterpillars: Artificial Intelligence and Sprites Chapter 3 - Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+ Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay Chapter 9 - D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code Bonus Chapter Porting .Nettrix to Pocket PC Appendix A - The State of PC Gaming Appendix B - Motivations in Games Appendix C - How Do I Make Games? Appendix D - Guidelines for Developing Successful Games Index List of Figures List of Tables Managing Players There are three operations we must code to equip our NetworkGame class with basic user management capabilities: SetUserInfo , which will enable the program to give the local player's name; PlayerCreated , which will trigger events in the main application to inform the host that a new player has connected to a given session; and PlayerDestroyed , which will be called when a player has disconnected. The next code listing presents the first of these methods, which will call the SetPeerInformation method of the Peer object to set the player data. This same method can be used to set information about the server and groups, if we need it to. Public Sub SetUserInfo(Optional strPlayerName As String = "") If strPlayerName <> "" Then PlayerName = strPlayerName End If PlayerInfo.Name = PlayerName DPPeer.SetPeerInformation(PlayerInfo, SyncFlags.PeerInformation) End Sub The following listing presents the code for the event handlers that will manage the player events sent by the Peer object. We'll also use these methods to update the PlayerCount property, which will store the number of players in the current session. Public PlayerCount As Integer = 1 ' Start Counting the local player ' Events used to handle Players Public Event NewPlayer(Name As String, ID As Integer) Public Event RemovePlayer(PlayerId As Integer) Private Sub PlayerDestroyed(sender As Object, _ dpMsg As PlayerDestroyedEventArgs) Handles DPPeer.PlayerDestroyed ' Send an event informing that the player is out from our session RaiseEvent RemovePlayer(dpMsg.Message.PlayerID) ' Update our number of players PlayerCount -= 1 End Sub Private Sub PlayerCreated(sender As Object, _ dpMsg As PlayerCreatedEventArgs) Handles DPPeer.PlayerCreated ' Get the PlayerInfo and store it Dim dpPlayerInfo As PlayerInformation dpPlayerInfo = DPPeer.GetPeerInformation(dpMsg.Message.PlayerID) If Not dpPlayerInfo.Local Then ' This isn't me, send an event with this player data RaiseEvent NewPlayer(dpPlayerInfo.Name, dpMsg.Message.PlayerID) ' Update our number of players PlayerCount += 1 Else ' Store our player ID number PlayerID = dpMsg.Message.PlayerID End If End Sub .NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen Hatton ISBN:1590590511 Apress © 2003 (696 pages) The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft's Visual Studio. Table of Contents .NET Game Programming with DirectX 9.0 Foreword Preface Introduction Chapter 1 - .Nettrix: GDI+ and Collision Detection Chapter 2 - .Netterpillars: Artificial Intelligence and Sprites Chapter 3 - Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+ Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay Chapter 9 - D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code Bonus Chapter Porting .Nettrix to Pocket PC Appendix A - The State of PC Gaming Appendix B - Motivations in Games Appendix C - How Do I Make Games? Appendix D - Guidelines for Developing Successful Games Index List of Figures List of Tables We are now able to create and list hosts, create a session and connect to a remote one, and manage players in our NetworkGame class. All we need to do now to complete our class is to code the message handling routines, which we do in the next section . Handling Messages Both the host and the clients will have to include code for methods to send messages and to handle received messages. To send messages is simply a matter of calling the SendTo method of the Peer object. This method receives a network packet with the message content to send, the chosen timeout, and the ID of the remote player. We can send messages to all other players by specifying zero as the remote player ID. The last parameter in this method lets us specify the message characteristics, like the priority or whether the message will loop back to the sender or not. The flags used in the following code sample will suffice for any simple game: Protected Sub SendData(message As NetworkPacket) ' timeout 200 ms ' Server ID = 0 send messages to everyone DPPeer.SendTo(0, message, 200, SendFlags.NoLoopback Or SendFlags.NoCopy) End Sub DirectPlay gives the result of the send operation by firing the SendComplete event of the Peer object. We can handle this event and generate an error event for the application if anything goes wrong, as presented in the next code listing: Public Event SendError(errCode As ResultCode) Private Sub SendComplete(sender As Object, _ dpMsg As SendCompleteEventArgs) Handles DPPeer.SendComplete ' Send an error event if we couldn't send the packet If dpMsg.Message.ResultCode <> 0 Then RaiseEvent SendError(dpMsg.Message.ResultCode) End If End Sub As for the arriving messages, we won't include any special treatment in the NetworkGame class, since every game must define its own set of messages. We'll instead include the code for an overridable function that receives a network packet, and that will effectively be coded in the derived classes, as presented in the following code sample: Private Sub MessageReceived(sender As Object, _ dpMsg As ReceiveEventArgs) Handles DPPeer.Receive ProcessGameMessage(dpMsg.Message.ReceiveData) End Sub Protected Overridable Sub ProcessGameMessage(message As NetworkPacket) ' This function must be coded by the derived classes ' that will handle the message received according to ' the game needs End Sub [...]... multimedia games using Managed DirectX 9.0 and Protected Overrides Sub ProcessGameMessage(Message As NetworkPacket) programming Dim Msg As GameMsgwith Visual Basic NET on Everett, the latest version of Microsoft' s Visual Studio Msg = CType(Message.Read(GetType(GameMsg)), GameMsg) RaiseEvent MessageArrived(Msg.PlayerId, Msg.MessageCode) Table of Contents End Sub NET Game Programming with DirectX 9.0... Netterpillars II NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen Hatton Apress © 2003 (696 pages) ISBN:1590590511 The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic NET on Everett, the latest version of Microsoft' s Visual Studio Table of Contents NET Game Programming with DirectX 9.0 Foreword... objGameEngine.NetWorkType = clsGameEngine.enNetWorkGame.Client Case DialogResult.Cancel Exit Do End Select WinGameField = New frmGameField() WinGameField.Show() Application.DoEvents() 'Creates a copy of the background image to allow erasing the sprites objGameEngine.BackgroundImage = WinGameField.PicGameField.Image.Clone NET Game Programming with DirectX 9.0 objGameEngine.CreateGameField(WinGameField.PicGameField.Handle)... interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic NET on Everett, the latest version of Microsoft' s Visual Studio In the next section, we'll discuss the updates we need to make to the GameEngine class to include multiplayer features in our game Table of Contents NET Game Programming with DirectX 9.0 Third Draft: Adding Multiplayer Features to the Game Engine Foreword... multimedia games usingall we need to do 9.0 and define the message flow project for our multiplayer game, Managed DirectX is clearly programming with Visual define each type of message we'll use in our game between the server and the client, and to Basic NET on Everett, the latest version of Microsoft' s Visual Studio Table 8- 1 presents all the game messages with details Table of Contents Table 8- 1: Netterpillars... latest programming with Visual Basic NET on Everett, the If NetWorkTypeof enNetWorkGame.No Then version Microsoft' s Visual Studio ' Update to network game: send the player movement to the oponent If Not DirectionSent Then Table of Contents DirectionSent = True NET Game Programming with DirectX 9.0 = Player1.Direction Player1.Direction Foreword If NetWorkType = enNetWorkGame.Host Then Preface GameClient.SendNetterDirection(Player1.Direction)... multimedia games using Managed DirectX 9.0 and In this case, all we do is present an error message to the local player, as shown in the next listing: programming with Visual Basic NET on Everett, the latest version of Microsoft' s Visual Studio Sub GameClient_SessionTerminated(msg As TerminateSessionMessage) _ Handles GameClient.SessionTerminated Table of Contents If Not GameOver Then NET Game Programming with. .. multimedia games using Managed DirectX 9.0 and programming with Visual Basic NET on Everett, the latest version of Microsoft' s by creating a In this chapter, we'll go back to basics Visual Studio very simple game with a few dozen lines of code to Overview reinforce the ideas you have encountered in this book: Creating games can be simple, and, most of all, it can be fun Table of Contents NET Game Programming. .. interesting multimedia games using Managed DirectX 9.0 and Event programming with Visual Basic NET on Everett, the latest StartDeathMatch() Event version of Microsoft' s Visual Studio EndDeathMatch( PlayerKilled As Integer) Event NetterDirection( playerId As Integer, Direction As Integer) Table of Contents ProcessGameMessage(Message As NetworkPacket) Overrides Sub NET Game Programming with DirectX 9.0 Select... produce interesting multimedia games using Managed DirectX 9.0 and to the remote machine programming with Visual Basic NET on Everett, the latest version of Microsoft' s Visual Studio 13 Both machines end the game at the same time Tip Review these steps until you are sure you understand exactly what we'll do in the coding phase Table of Contents NET Game Programming with DirectX 9.0entering the code phase . multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft& apos;s Visual Studio. Table of Contents .NET Game Programming with DirectX. multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft& apos;s Visual Studio. Table of Contents .NET Game Programming with DirectX. multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft& apos;s Visual Studio. Table of Contents .NET Game Programming with DirectX

Ngày đăng: 12/08/2014, 20:22

Từ khóa liên quan

Mục lục

  • The Game Proposal

  • The Game Project

  • The Coding Phase

  • Adding One Final Touch

  • Summary

  • Chapter 9: D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code

    • Multithreading

    • Creating Nonrectangular Windows

    • Accessing Nonmanaged Code

    • The Game Proposal

    • The Game Project

    • The Coding Phase

    • Adding the Final Touches

    • Summary

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan