UWP Game: Where to Start

  • Tutorial
Hello, Habr! Today we are launching an experimental series of articles. You will immerse yourself in a reality show for self-taught programmers, in which Alexei Plotnikov , one of the members of our Microsoft Developer community, will talk about how he creates the game on UWP. Under the cut - the first part, with a description of the project idea and the answer to a simple question: "What needs to be laid from the very beginning?" Do not forget to leave comments, you can influence the development process.



Прежде чем запустить данный эксперимент, мы проводили опрос на эту тему. С его результатами можно ознакомиться здесь .
I give the floor to the author.


Intro


Let's start with the acquaintance. My name is Aleksey Plotnikov and was previously referred to as an “Active Community Member” in this blog. This is the most comprehensive presentation, since I am not an employee of the company and, even, I am not a professional developer. I am a self-taught programmer using VB.NET as the development language, the author of several articles, a couple of interesting projects and hundreds of useful answers on MSDN forums. However, despite the fact that development is just a hobby for me, I have extensive experience, which I plan to share with you in this cycle.

By the way, about the content. It will focus mainly on newcomers to UWP, but experienced in development in general. This cycle is ideal for WPF developers and developers of other platforms who have decided to try themselves in the development of UWP / .Net. And taking into account the constant references to the documentation and guides from MS, the cycle will probably be affordable for beginners who want to get acquainted with .Net development, starting with UWP, and who are not lazy to read not only step-by-step manuals, but also dry documentation. However, certain topics of the cycle may be useful for experienced developers, as they plan to touch on some life hacks and even work around unsuccessful decisions in the documentation, which for some reason you blindly performed.

And before we begin to get acquainted with the future project, on the basis of which the cycle will be built, I want to devote a couple of lines (or maybe a couple of paragraphs) to discussions about why this is needed at all. To be honest, developing a Windows store is at least not fashionable. A cool idea, implemented as a mobile application, will bring a lot of money on iOS and millions of users on Android.

There are at least a few reasons to study UWP development using .Net. Firstly, if you are a WPF developer, then the migration will be as smooth and painless as possible for you. Secondly, no matter how cool other mobile platforms are, they still remain “mobile”!

The Universal Windows Platform in its very name speaks about the capabilities embedded in this platform and the breadth of potential devices on which your application can run. Of course, you will be right if you say that now Windows 10 is mainly used on desktops, but a rapidly changing market can change the balance of power in favor of Windows 10 as the most popular OS on all possible devices in two respects. So why don’t we take advantage of such “mobile” conveniences as automated distribution, convenient publishing and updating, on the whole spectrum of devices, and not just on mobile?

Finally, it's time to talk about the project on the basis of which this cycle will be built.

The idea of ​​the project arose in the wake of the popularity of cryptocurrencies and is a fairly simple game. The game will be called "Crypto Farm" and, as you probably guessed, the game process will be built on cryptocurrency mining. A more detailed description of the gameplay will be considered during the cycle in those articles where it will be necessary. It is important to understand that this cycle is about developing on UWP, and not about this game, so it will only be a support for articles that I will try to make as abstract and applicable to different, not just game, scenarios.

During the development and writing of the articles, I plan to cover the following topics:

  • Создание проекта. What you need to lay from the very beginning to get maximum convenience and expandability in the future.
  • Start screen. More lively and more interesting outside, effective inside.
  • Multiuser elements. User identification. How? Where to store data? How much is it?
  • Application structure How many pages are needed. Transitions between them.
  • Design and styling. Several articles on the appearance of the application. From preparing graphic materials to styling controls.
  • Create your own controls. When the available is not enough and you need to create your own.
  • Background events. Live tiles and notifications. Important elements of user interaction that must be present in every UWP application.
  • Monetization. Types of earnings. Which way to choose and how to integrate effectively.
  • Debugging on different devices, resolutions and aspect ratios.
  • Build and publish the application.
  • Support after publication. Work to achieve high ratings and positive reviews.

This is not a complete list of topics that are planned to be addressed and, probably, many will arise due to your reviews of articles as they appear. Also, I plan to devote several articles to emerging difficulties and mistakes.

But, perhaps, the preface is enough and it's time to start developing.

Создание проекта. What needs to be laid from the very beginning?


If, after reading the headline, you suddenly decided to skip this article, thinking that with the creation of the UWP project you will not have any difficulties, you will be right only partially.

On the one hand, it is very difficult to make critical mistakes at such a simple stage. But on the other hand, you can significantly simplify your life by doing everything right from the very beginning. In addition, at the end of the article I will share my personal preferences regarding the creation of the project, which may be useful to experienced developers.

I will create my project in the Russian-language Visual Studio Professional 2017. This edition is paid, or is available by subscription (as in my case), but it is optional for full work on the UWP application. You just need to download the free Visual Studio Community on the official website of Visual Studio.

For some reason, many novice developers believe that applications created in Community are forbidden to publish on a paid basis or in any other way, to earn money on development in this edition, but this is not true. Until you become a large company, whose main source of millions of revenue is application development, you can safely use Community without fear of claims from Microsoft.

So, we start Visual Studio (hereinafter VS) and, if you have not changed anything, we immediately see the start screen. This screen contains quick access to opening and creating projects, as well as the latest news for developers. Since this screen changes from version to version, I will not refer to its items, but in the old way I will go to the menu "File> Create project ...". In the window that opens, a list of templates of all projects that we can create in this version of VS is sorted by type and programming language.



We need the “Universal Windows Applications” section and the topmost template “Empty Application (Universal Windows Application)”. By the way, if you were developing applications for Windows 8 / 8.1, which were indicated by the abbreviation WinRT, then remember that the list of templates was not limited to an empty application. There were also additional multi-page application templates that meant quickly creating a project based on your data.

I must admit that the presence of these “quick” templates, in my opinion, was a mistake that led to the creation of thousands of unattractive and similar applications that flooded the Windows store and this slightly spoiled its image. Although, on the other hand, then the Windows store just appeared and it was critically lacking in content.

Having chosen the desired project template, you need to select its name, location and again the name, but this time for a solution. The solution in VS is the union of several projects together, which, by the way, I will separately discuss in one of the following articles. In principle, at the stage of the initial project creation, its name and the name of the solution can be left the same. Separately, it is worth mentioning the name of the project in Cyrillic. In principle, no one forbids you to use the Russian text in the title or even use spaces, but old programmer scars begin to scratch a lot from such actions. By giving the name of the project in Latin and without spaces, you will definitely save yourself from any potential problems with storing and synchronizing the project, so I recommend that you do just that.

It also remained to decide what to do with the two checkmarks in the lower right corner of the project creation window. The first one (“Create a directory for the solution”) will help you if you choose a shared folder instead of prepared in advance as the target location for the project. A very convenient feature and it is not in vain that it is marked by default. The second item of additional parameters, called “Add to version control system”, we will leave unchecked, and later in the article I will explain why.

So, the coveted “OK” button is pressed and, it would seem, you can begin to study the structure of the project, but no. Before us is another dialog box offering to select the target and minimum versions for your UWP application.



If you are a developer of WPF or other projects in VS and have already begun to yawn from the previous paragraphs, then it’s time to wake up, because we have a very important choice that significantly affects the number of potential users, as well as the development work effort. I must admit, I am very surprised that in most manuals we are prompted to just click "OK", without changing anything, completely not understanding the topic. I, not so much for readers, as in my time, for myself, carefully studied the issue and now I am sharing my thoughts with you.

The most obvious thing that comes to mind when trying to figure out a question is to click on the link in this window, which will lead us to the documentation page with a description of these parameters. A rather useful page, which, unfortunately, practically does not answer the question “Why do we even need to drive ourselves into some kind of framework?” and the conscious choice of these very frameworks does not make it much easier.

I will begin by answering the question of what caused this framework to appear. It's all about Microsoft marketers who said that the company needs to release an OS with one name, and then complement and improve it, attributing only version numbers. And these numbers should be displayed only in the information about the system and not especially stick out. As a result, all that an ordinary user knows is that Windows 10 is installed on his computer (or other supported device), which is periodically updated for some reason. This is a very smart decision, since even the very first and almost forgotten build of Windows 10 still remains Windows 10 and works to the benefit of general statistics. And for us, as developers, this is also extremely beneficial, because over time, the army of potential users of our application will only grow.

Unfortunately, the fee for this approach is that we need to carefully monitor the use of new features in the application to ensure its maximum compatibility on a wider range of Windows 10 builds, because, as you know, the features available only in build 16299 will not work with the user of assembly 10240.

But I did not answer why we need a range of versions. The choice of the minimum and the target version is due to the ability to make our application adaptive to different builds of Windows 10 with minimal casualties. We do not need to sacrifice functionality for the sake of maximum coverage, or, on the contrary, coverage for the sake of new functions. We are offered to choose how much we are ready to sacrifice each individual item, but in any case we will have to sacrifice. Even if you select the maximum range - from the earliest to the latest version - and get maximum coverage and a full range of functions, we will have to devote a lot of time to adapting the code, which will significantly stretch and complicate the development process.

На заметку! Адаптивный код – это специальные условия в программе, определяющие, доступна ли нам та или иная функция. Такое условие позволяет, с одной стороны, использовать новые функции там, где они доступны, а с другой — позволить приложению без ошибок работать в тех версиях Windows, где этих функций еще нет. Примеры адаптивного кода будут появляться в дальнейших статьях этого цикла.
So, what should you choose as the target and minimum version? For the target version, I recommend choosing the highest possible value. It is important to understand that with each update of Windows 10, not only new features appear, but old ones also improve. Whereas applications aimed at early assemblies will use exactly the API of the assembly they are aimed at. Therefore, choosing the latest version as the target, we get not only new functions, but also better and more modern old ones. Knowing this, we can also decide when to choose an earlier assembly as the target. And this is only necessary if the mechanisms that we plan to use have stopped working in the latest builds.

For example, this can happen if the application is transferred from another platform or simply when using “crutches” based on outdated API features. Just in case, I’ll add that the target version should not be perceived by you as the maximum. Of course, your application will continue to work properly in future versions of Windows, but it will refer to the version of the API that it is aimed at.

Let's move on to the minimum version. I recommend setting it equal to that version of Windows, which is currently the statistically most popular version. So we get maximum users, depriving ourselves of the extra hassle of checking the compatibility of the code for a particular version. Naturally, if you are sure that your user is stuck on an earlier build, then you should choose it as the minimum. But choosing the same for the target and minimum versions is not the best idea. Updating Windows is not only not fast, but in the end it does not cover all old computers, so driving an application into a single assembly is not justified.

Finally, all the preludes have been completed and you can begin to study the contents of the created project. You can examine its files and folders in the "Solution Explorer" window.

Let's figure it out:

  • Folder Assets . As planned, you should store the resources of your application in this folder, such as, for example, pictures. By default, this folder contains mandatory patch images that act as a logo, and I’ll talk about them in more detail in one of the articles in this series. By the way, you do not have to store these and other resources in this folder. As a matter of fact, you have no restrictions on the number of folders and subfolders with resources.
  • The App.xaml
  • file and its associated App.xaml.cs / vb perform almost the same function as Application in WPF. In App.xaml, you can register application resources, as well as specify your preferred theme (light or dark) in the RequestedTheme property. In the code file, you can control the life cycle of the application. The theme of the life cycle of UWP applications is quite extensive, and you can read more about what it is here. . Also, the App.xaml.cs / vb file can be used to host global application variables, but this already depends on the programming pattern that you decide to use. For example, MVVM is more like UWP, which I will not use, but I highly recommend it to experienced developers.
  • The App1_TemporaryKey.pfx
  • file is a temporary certificate that signs your application and is needed so that it can run on the device. We don’t need to know anything more about him. We will not have to work with him.
  • The MainPage.xaml
  • file and associated MainPage.xaml.cs / vb is the main page of the application. The difference from WPF applications is that here we are working not with windows, but with pages. The window of the UWP application is most often one, and the pages of the application are loaded in it, between which you switch, like navigating through the pages of a site in a browser. I’ll talk more about pages and navigation in UWP in a future article.


  • And the last automatically generated project file is the Package.appxmanifest
  • file . This, as you understand, is the manifest of the project, which contains the main declarations. This file has a convenient editor that is called by a double click. In this editor, you can set important application parameters, set the location of logos, set the capabilities of the application and announce the contracts that it will use. In the course of this cycle, I will regularly refer to different manifest settings and consider them in more detail. I also note that in the documentation there is often an indication in which manifest parameters which keys should be marked. In these cases, the documentation refers to a text version of the manifest. You can open it if you right-click on the manifest file and select "Open with ..." and then - "Editor (text) XML".

The newly created project is fully operational, and you can start it by pressing "F5". After starting the application, it will appear in the list of installed applications in the Start menu, from where it can also be launched.

And the last thing I want to mention is adding a project to the version control system. There are several popular version control systems (hereinafter referred to as Git), but for a novice developer Team Services is best suited. This is a free tool for publishing applications in remote storage, as well as for team development. Even if you do not need such powerful features as working together on a project, creating code branches and individual builds, it is very difficult to underestimate the ability to synchronize and backup.



So, we will publish the newly created application in Team Services. To do this, in the lower right corner of VS you need to click on the inscription “Add to version control system> Git”. In the opened window “Team Explorer - Synchronization” click on “Publish Git repository”.

In order for the subsequent manipulations to go smoothly, you must be registered on the Team Services website and have your own domain in this system. This is done quite simply. In the main synchronization window, click the Learn more link, which will send you to the Team Services website. On this site, select "Get started for free" and follow the instructions. After creating your domain, it will become your hub in which you can track projects, view the history of changes, assign a team and much more, but now we just close the site and return to VS.

After the preparatory work, select "Publish Git repository", and now it remains only to select your account, domain name and publish the project. If everything went well, then the synchronization window displays a list of actions that you can take directly from VS. We are most interested in the items “Changes” and “Synchronization”.

In fact, we still haven’t uploaded the entire project to Git. First, we need to fix all the changes made to the project, which include the creation of the project. To do this, go to the “Changes” section, fill out the description of the changes made, and then click on “Commit All”. Team Services allows you to track the history of changes made to the project, and - if necessary - return to an early point, or just see what and when we added, so choose a descriptive description that will help you quickly find the right point in the development process in the future. For example, now we can indicate in the commit description: “Creating a project”.

After all the changes are committed, they need to be synchronized with Git. To do this, go to the "Synchronization" section and select the appropriate link. Synchronization works both ways, and if you commit and upload the changes to another computer, then at the time of synchronization they will be loaded on that. It is also convenient if you have lost project files that you previously uploaded to Git. Just sync the project without a local commit, and they will return.

On this topic, the creation of a UWP project can be considered closed, however, since this series of articles is written in parallel with the development of a live project, I decided to supplement this article with personal recommendations on the initial setup of the project that I developed in the process of working with UWP.

The information below is directed to WPF developers, is a personal experience and should not be taken as a reference.

In fact, it was not in vain that I recommended to ignore the “Add to version control system” checkbox at the very beginning of the project, although I then described this process without changing anything in the project. I myself publish only after adding some experience-based additional elements to the project.

Firstly, the ConvertersAndStyle folder is added to the project , into which I put the files with converters and resource dictionaries:

  • The Converters.cs / vb file is a regular class file in which the converters used in the application are then placed.
  • The File ConverterDictionary.xaml is a file of the "Resource Dictionary" type, in which we will write links to our converters. Since most of the converters will be used throughout the application, it is better to define them in one file, and not in the resources of each individual page.
  • The ApplicationStyle.xaml
  • file is also a resource dictionary, and in it we will define all the resources associated with the application style.

As you probably understood, I chose the names of folders and files based on their functions. You can give them any names convenient for you.

After adding the resource files, we need to add an indication of them in the App.xaml file:

<Application x:Class="CriptoFarm.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:CriptoFarm" RequestedTheme="Light">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="ConvertersAndStyle/ConverterDictionary.xaml"/>
                <ResourceDictionary Source="ConvertersAndStyle/ApplicationStyle.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Now we can access the resources from these files anywhere in the application.
The second thing I want to note is the allocation of a separate folder for the image. Since I often write paths to pictures manually, I use simpler and more intuitive names of folders and files. The main folder for storing images in my projects is named Images , and I use the Assets folder only for logos - those that appear on the tile, in the application list and in the store.

Next, prepare our application for localization. To do this, create at least two folders. The first for the native language (in our case, Russian) should be called "ru", and the second for the international - "en". In this case, folder names play an important role and you do not need to name them differently. You can also add folders for additional languages ​​if you plan to localize the application in several languages. A complete list of available folder names for different languages ​​can be found here .

In each of the folders you need to add a file of the type “Resource File (.resw)”, leaving its default name. In more detail about the localization of the application and what to do with these files later, I will tell in a separate article in the series.

And after all these manipulations, you can publish the application to the version control system, after which the project is completely ready for immediate work.

The next article in the series will be devoted to creating your own start screen, and I hope it will bring something new against the background of existing articles on this topic.