How to make a sea battle online on Silverlight 4 (detailed article)

    Good afternoon! This text is a detailed article on how I did a naval battle on Silverlight 4. Your comments inspired me to write the article. Source codes can be taken here . Test login test@mail.ru, password 123456. But there is a limitation on the fact that players must have different logins. Therefore, someone alone must be registered, otherwise an error will occur that will be fixed soon.
    image

    So, I am a certified specialist in various fields, but I had 0 knowledge of WPF (what Silverligh is based on). Therefore, I decided to study the basics of this technology based on a living example, which became a sea battle familiar from childhood. Taking into account the above, this article does not describe the optimal mechanisms for using technology, because, for sure, there is a more elegant solution.
    In general, what we need: Visual studio 2010 (I have the Ultimate version, but I think you can try it on the free Visual Web Developer 2010 Express version), and you also need to install Silverlight 4 tools for VS 2010. After everything has been downloaded and delivered, you can get down to business! First we need to create a host application on ASP.NET (File-New Project - Web Application). I have already created it in advance, and there Membership (MS SQL) must be configured there. You can read more about this here . The main element of membership will be a table from the Users database, since the logic of working with users is based on it. Also add that profiles are used. To configure them, insert the following lines in web.config:
    profile enabled = "true" element defaultProvider = "SqlProfileProvider", add the
    add name = "NickName" element to the properties subelement .

    Now everything is ready to create a silverlight application! We go into File-AddNewProject, select the Silverlight Application, point out our host application, and also check the box for the future: Net RIA Services. So, our application is ready. Upon creation, a test page will automatically appear in the hosting application for launching the silverlight program. We will adjust the parameters for launching the application and add this lineinto the object element. Such a literal will serve us as parameters to which we will pass the address of our web service (since it is one for local testing, but on the hosting it will be completely different): Then we will read these parameters in the silverlight program: So, it’s more logical to tell about the inner kitchen programs. We will need to create 5 tables in the database:
    StringBuilder SB = new StringBuilder();
    SB.Append("треуг.скобкавлево param name=\"InitParams\" value=\"");

    SB.Append("SFServiceUrl="+GetServiceUrl());

    SB.Append("\" /треуг.скобкавправо");

    LiteralParams.Text = SB.ToString();



    private void Application_Startup(object sender, StartupEventArgs e)
    {
    // Получаем адрес сервиса
    ServiceUrl = e.InitParams["SFServiceUrl"];



    image
    It is not necessary to establish connections, as they are clearly not used in our core yet. Cropped strips go to the Users table, UserId field. Then you will need to create a data context (Linq To SQl) and add these tables to it. In the future, the data context will have the name of the SDC class. It should be placed in a separate assembly (say, SDataAccess). I will not describe how to do this, because This is the topic of a separate article. Apparently, in order to use Domain services, it is better to make a data context based on LinqTo Entities, but I decided to do it the old fashioned way.
    As a kernel, I use the Workflow Activity Library (SWorkflows):
    image

    In it, create the folder Activities / SeaFight. Its contents are in the source. The main logic of the game is protected there, such as: creating, completing, checking moves, receiving data about players, keeping a chat, working with ship coordinates, etc. In more detail you can familiarize with classes in source codes which lie in the Activities \ SeaFight folder. Linq to Sql queries are used there, and query results are issued through the Workflow service to our Silverlight application.
    After our assembly with activities is successfully compiled, we can safely proceed to create a Workflow service. To do this, in our host application, create it: File-Add New Item - Workflow Service:
    image
    Then you need to open this XAMLX file and start creating the service. Unlike Workflow from .Net 3.5, Workflow-first authoring is used here, which facilitates the task of creating an interface. Previously, you had to first make an interface with the attributes ServiceContract, OperationContract, etc., and then use it to create a workflow, and now this interface is automatically generated based on the workflow. So, in order for our service to process several operations at once within one Workflow, we need to insert Peek Activity in the root, and then add it to the separate Branch (branches) of the Receive Activity and Receive-Send Activity. Inside Receive Activity, you need to embed our activities, which we did in a separate assembly. They will be automatically available on the Toolbox tab:
    image
    Now, sequentially creating separate branches, you need to arrange activities on Workflow. Next, add the variables for the necessary activities (the variables tab is at the bottom left), and then bind all this (for more details see the source code - SeaFightService.xamlx). For Receive activity, you need to set the interface (ServiceContractName) and the name of the operation, and bind the input parameters to variables. Remember to check the CanCreateInstance box for each Receive Activity. Read more about this on the workflow website .
    Here's how I got it:
    image
    Now that our business logic is ready for the game, we add the Service Reference to our Silverlight project (Add Service reference, then select Discover):
    image
    Now it remains only to make our game interface and use business logic by calling a proxy object. Here's how I used the proxy object: And here is the method that processes the response of the WCF service: The project has 5 windows: a game creation window, a second player waiting window, a ship placement window, a battle window, and a results window. Accordingly, they are all in the source, and you can familiarize yourself with their composition in more detail. As the playing field, I used the standard component - Grid, and the positions of the ships are indicated by the standard ToggleButton with the changed Content property. Again, to find out how everything is done in detail, see the source code for the SeaFight project.
    var proxy = ProxyReference.GetProxy();
    try
    {
    proxy.GetGameListCompleted += new EventHandler треуг.скобкавлево GetGameListCompletedEventArgs треуг.скобкавправо (proxy_GetGameListCompleted);
    proxy.GetGameListAsync(proxy);
    }
    catch
    {
    proxy.Abort();
    }





    // Обновляем список доступных игр
    void proxy_GetGameListCompleted(object sender, GetGameListCompletedEventArgs e)
    {
    var games = e.Result;
    dataGridGames.ItemsSource = games;
    ((SeaFightServiceClient)e.UserState).CloseAsync();
    }




    To switch windows, the PageSwitcher element is used, which stores the current window in its root Content property. To switch between windows, I use this code: One of the most important drawbacks of the project is the lack of duplex mode in the network service. Therefore, to update the state, the System.Windows.Threading.DispatcherTimer timer is used. Because of this, there is a delay between receiving messages and moves in the game. In the future, it is still planned to switch to duplex mode, but this is not an easy task for Silverlight. This is what the ship placement window looks like:

    if (this.Parent is PageSwitcher)
    {
    PageSwitcher ps = this.Parent as PageSwitcher;
    ps.Navigate(new MainPage());
    }



    image

    I would like to note that there is one more auxiliary project: SEntities, which contains common classes for the kernel and silverlight applications. It is more correct for the future to use a special type of assembly - Silverlight Library, rather than the usual Library, which is now.
    In general, this is where I end this article, since the main points are described by me, and another such article for each function can go into the description of individual functions. Therefore, for more detailed details (how to make the placement of elements on the form, etc. you can contact MSDN or me). If you want to help in the development of this project - write: squalsoft {at} mail.ru.

    Also popular now: