In the previous part of this series we create the gameplay. In this part we’re going to add a scoring mechanism and add some UI that shows that. I also want to change the start of the game a little by randomizing the tiles, because the solution is way to simple: Just click all the tiles once and you’re done. Maybe in a future part we’ll make an editor to create patterns of colors. Let’s start with the randomization.

Randomizing Tiles

Both changes are made in the code, in the LevelController to be exact. I added a line to the Start method.

t.Row = j;
t.Column = i;
t.Clicked = TileClicked;
t.CurrentColor = Random.Range(0, t.Colors.Length);
tiles.Add(t);

On line 28 you can see the CurrentColor being set to a random value in the range 0 to the number of colors available. This will cause the tile to have a random color and always use the total number of colors available. Even if we choose to change the number of colors in the future, it still works.

That’s it. When you run the game, it should be all random.

image

Some project reorganization

Since the project is growing, and will continue to do that, I believe it would be best to do some reorganization. To enable the scene to be in different states I’d like to have the generated tiles inside another GameObject. Add a new empty GameObject to the scene and call this one “Level”. This will be the parent of all tiles and it’ll also contain the GUI that’s shown during gameplay.

To make the tiles have this “Level” GameObject as a parent we’ll have to make some adjustments to the LevelController Code. First add a new public GameObject to the class and call this “LevelRoot”.

public int NumberOfRows = 7;
public int NumberOfColumns = 7;
public GameObject LevelRoot;
public TileComponent Tile;

private List<tilecomponent> tiles;

Than, inside the loops in the Start method, set the transform.parent property of the tile to the transform property of this LevelRoot GameObject as shown in row 31 below.

t.Row = j;
t.Column = i;
t.Clicked = TileClicked;
t.CurrentColor = Random.Range(0, t.Colors.Length);
t.transform.parent = LevelRoot.transform;
tiles.Add(t);

I also would like to have the controller scripts together. In an earlier part of the tutorial we’ve added the LevelController to the camera, let’s move it to its own container.

Add a new GameObject to the scene called “Controllers” and add another GameObject to that as a child called “LevelController”. Now, select the camera and look for the LevelController script in the inspector. Drag that script from the camera to the GameObject “LevelController” we’ve just created.

Last thing to get it all working is to drag the “Level” GameObject to the LevelRoot property of the LevelController.

SNAGHTML12d62e8

Run to test game. Nothing should have changed to the workings of the game. If you look at the hierarchy panel when the game is running you should see a whole list of tile objects inside the Level GameObject.

Adding a score

The scoring needs a ScoreController. So, lets add a new empty GameObject to the Controller object and name it “ScoreController”. Add a new script to the scripts folder and name that “ScoreController” too. Add the script to the GameObject by dragging it onto there. Double click the script to open it in Visual Studio.

using UnityEngine;
using UnityEngine.UI;

public class ScoreController : MonoBehaviour {

    private int CurrentScore;
    private LevelController levelController;
    public Text Text;

    public void Start()
    {
        levelController =
                GameObject.FindGameObjectWithTag("LevelController")
                .GetComponent<LevelController>();
    }
    public void OnEnable()
    {
        LevelController.ScorePoints += LevelController_ScorePoints;
    }

    public void OnDisable()
    {
        LevelController.ScorePoints -= LevelController_ScorePoints;
    }

    private void LevelController_ScorePoints(int points)
    {
        this.CurrentScore += points;
        Text.text = this.CurrentScore.ToString();
    }
}


The way the score is updates is though events raised by the LevelControler. To prevent memory leaks the event handler is attached in the OnEnable method and detached in the OnDisable method. The Text property on line 8 is going to hold a reference to a text object in the scene that we’ll create in a sec. For finding the LevelController I want to introduce another technique, by using a Tag. How to create the tag itself we’ll go over too, but from line 12 to 14, in the Start method, you can see how this is done. When the game grows and more tags, or other strings, are used in my game, I might refactor this to come from a class containing constants to prevent bugs.

The second piece of code that has to be extended is inside the LevelController. I added the actual event in the last lines below. Raising the event is nothing more that calling a method (line 44). I always check for null, just in that rare case there’s no event handler attached.

private void TileClicked(int row, int column)
{
    tiles.Where(t => t.Row == row || t.Column == column)
         .ToList()
         .ForEach(d => d.NextColor());

    if (ScorePoints != null)
    {
        ScorePoints(1);
    }
}

public delegate void ScoreEventHandler(int points);
public static event ScoreEventHandler ScorePoints;

Back in Unity we’ll need to create a new Empty GameObject as a child to the Controllers GameObject, and call it ScoreController. Drag the new ScoreController script to ScoreController GameObject.

Every GameObject can be marked with a Tag. Select the LevelController to set its tag.  As you can see at the top of the Inspector the LevelController is “Untagged”. To add a new tag, click the drop down next to “Tag” and select “Add Tag…”. Click on the little ” + ” below Tags and enter “LevelController”. Select the LevelController GameObject again in the Hierarchy and, again, open the dropdown next to Tag in the Inspector. You should see “LevelController” as an option. Select that and you’re done.

SNAGHTML2cee32

Now for the actual texts. Right click the Level GameObject in the Hierarchy panel and look for Text under the UI category. Note that the Text GameObject gets a Canvas as a parent.

Snap the text to the left top. By holding Alt and Shift while selecting the top-left icon, you can set the snap point and the hotspot to be in the top left corner.

image

Set the position to X: 10 and Y: –10 to give it just a little space from the edges. I gave it a width of 70 and a height of 30. I entered “Moves:” as text to show, set the font size to 20 and the color to black.

SNAGHTML50315b

Copy the text, you can do that by hitting ctrl+d in hierarchy panel and set the text to “0”. This text object will show the score.

Last thing to do is selecting the ScoreController in the Hierarchy and drag the Text object with for the scoring to the Text property of the ScoreController.

By now, the Hierarchy should look something like this:

image

And that’s it for part 3 of this tutorial. Nothing specific to Windows 10 this time. In the next part we’re going to add a title screen and a complete screen. We’re also going to add the last score to the current live-tile.

In part 1 of this series I showed you how to set up Unity, creating a prefab for the tiles and added the first script for generating a grid of tiles. In this second part I’d like to make the grid interactive and enable the change of colors for the rows and columns in the grid.

Tile behavior

Lets start by adding a new C# script to the scripts folder. I named this script TileComponent and opened it in Visual Studio. In the script we’re going to add some properties to the tile. First we need an array that will contain the various colors of the tile. We also need to keep track of the current color. This integer contains the current index of the the tile. To make things a little easier when changing the colors in a row and column, I also added two integers that are going to contain these.

public int CurrentColor;
public Color[] Colors;

[HideInInspector]
public int Row;
[HideInInspector]
public int Column;

By making these properties public we can change them from the Unity inspector. I don’t want the row and column properties to be edited in Unity, but I need them to be public to be able to access them from another class. The HideInInspector attribute marks fields hidden from the inspector.

Let’s switch back to Unity to add a few thing there.

To get the the script attached to the tile, first select the tile in the project explorer. Than, in the inspector, click “Add Component” and go to scripts. Alternatively you can search for it.

SNAGHTML25a9877

I added 4 colors to the array by setting the size to 4 and selecting the 4 colors I like to use for the tiles.

image

To get the tile to show the color, we need a material. Let’s add a new material to the materials folder by right-clicking on the materials folder and selecting “Create”->”Material”. I named my material “TileMaterial”.

image

Instead of using the default shader I want to use the “Unlit”->”Color” shader. This shader doesn’t have any other properties than the color.

image

To add the material to the prefab we need to drag the tile prefab to the scene hierarchy, open the “Tile” GameObject and drag the “TileMaterial” onto the “TileGraphic”.

SNAGHTML1ae31e

Make sure the change is applied to the prefab by clicking on the “Apply” button in the inspector.

image

You can safely delete the “Tile” prefab from the scene hierarchy now.

Before we do another test run, let’s switch to Visual Studio and add some more code.

using UnityEngine;

public class TileComponent : MonoBehaviour
{
    public int CurrentColor;
    public Color[] Colors;

    [HideInInspector]
    public int Row;
    [HideInInspector]
    public int Column;

    void Start()
    {
        UpdateColor();
    }

    private void UpdateColor()
    {
        this.GetComponentInChildren<MeshRenderer>().material.color = Colors[CurrentColor];
    }

    public void NextColor()
    {
        this.CurrentColor++;
        if(this.CurrentColor > this.Colors.Length - 1)
        {
            this.CurrentColor = 0;
        }
        UpdateColor();
    }
}

I added a new private method called UpdateColor. This method looks in the children of the GameObject where the script is attached to, the “Tile”, and finds a component of type MeshRenderer. The MeshRenderer contains the material. The color property of this material is set to the current color of the tile.

The Start method is executed when the Tile is activated and sets the color to its initial color.

I also added another method, NextColor. This method increases the CurrentColor index, but makes sure it’s reset to 0 when it exceeds the number of colors. After this change the color of the material is updated too.

Interaction

The game won’t be any fun until there’s some interaction. I’d like to handle the click on the tile in the LevelController we created in part 1 of the tutorial. The LevelController has access to all tiles. I’m adding a callback from the tile that the LevelController is going to subscribe to. The field is called “Clicked” and is an Action with two integer parameters which will hold the Row and Column of the clicked Tile.

public Action<int, int> Clicked;

To handle the actual click on the tile we can add the OnMouseDown method. Unity will automatically call this method when a mouse down event occurs.

public void OnMouseDown()
    {
        if (Clicked != null)
        {
            Clicked(Row, Column);
        }
    }

Just in case there’s nothing that handles the click I added a null check. If something is handling the Clicked action it is called with the row and column.

To get the Tile to register click events we need to add a collider in Unity. Select the prefab and click the “Add Component” button. Search for the “Box Collider 2D” component and add that.

image

To get the color of the tiles to change, we need to keep track of the created tiles from within the LevelController. Let’s have a look at the code and go over the changes.

 

using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class LevelController : MonoBehaviour
{
    public int NumberOfRows = 7;
    public int NumberOfColumns = 7;

    public TileComponent Tile;

    private List<TileComponent> tiles;
    void Start()
    {
        tiles = new List<TileComponent>();
        for (int i = 0; i < NumberOfColumns; i++)
        {
            for (int j = 0; j < NumberOfRows; j++)
            {
                TileComponent t = (TileComponent)Instantiate(Tile,
                            new Vector2(i - NumberOfColumns / 2f + .5f,
                                        j - NumberOfRows / 2f + .5f),
                            Quaternion.identity);

                t.Row = j;
                t.Column = i;
                t.Clicked = TileClicked;
                tiles.Add(t);
            }
        }
    }
    private void TileClicked(int row, int column)
    {
        tiles.Where(t => t.Row == row || t.Column == column)
             .ToList()
             .ForEach(d => d.NextColor());
    }
}

I changed the type of the “Tile” field to TileComponent. I also added a list of TileComponents to keep track of the ones created. In the Start method the list is constructed. I added a variable to hold the result of the Instantiate method in line 20. Because we added the Row, Column and Clicked fields to the TileComponent earlier we can set them here.

The TileClicked method contains some code that might look a little complex. I used the linq Where method to filter the list of TileComponents. I want all items where the row is equal to the row of tile that was clicked or where the column is equal to the column of that tile. I than convert the result back to a list to be able to use the ForEach method to go over the selected tiles. For every tile in the result I change the color the the next by executing the NextColor method.

One last thing before we can run the game. Because I changed the type of the “Tile” GameObject to TileComponent, we need to drag the prefab from the folder to property in the inspector in Unity.

You should be able to run the game now. Click around and the colors should change.

image

In part 3 we’re going to add some UI to show our current number of  moves.

9

There are various ways to develop apps and games for the Windows Platform. One of them is by using a great tool called Unity. Unity is a development environment and platform to build 3D and 2D games and interactive experiences. There’s a vast community of people creating, sharing and selling assets. The most awesome thing about Unity is that is has a free version you can use for your personal projects. It only shows a splash screen stating that the game is built with the personal version of Unity.

There are beautiful examples of games built with Unity (you definitely should look at the showcase), but for now I’ll focus on getting started.

The game I’m going to build is a going to be a simple puzzle game, it will be a clone of Alien Tiles. I’m going to use Unity 5 and Visual Studio 2015, both running on Windows 10. The game will show a grid of tiles with a particular color. When the player clicks a tile the entire row and the entire column of the tile will cycle to the next color. The goal of the game is to get the entire grid to a specific color.

Setting up Unity

Let’s start by opening Unity and create a new project. I’m going to name my game “ColorfulTiles” for now. To have Unity preconfigured for a 2D game, I select 2D from the options.

Unity Welcome Screen

Unity Welcome Screen

I also want to include the Visual Studio 2015 Tools Asset Packages, by clicking the Asset Packages button and checking the package “Visual Studio 2015 Tools”. And hit “Done” to close the package select window.

Asset Packages

Asset Packages

 

Now hit “Create Project” to create the game and get going.

I won’t be going over the various panels of Unity in detail in this tutorial, so I can focus on building the game. But, let me know if you would like me to write a tutorial about the details of the UI of Unity.

When starting a new project in Unity I always start by creating a few folders: Scenes, Prefabs, Materials and Scripts. Depending on the game I’ll be building I might add other folders (for sounds, textures, etc.), but for now this would be sufficient. You can add folders by right-clicking the project panel and going to Create -> Folder in the context menu.

Folders

Folders

 

Graphics

Before I start on the level generator I would like to add the tile to the game. I do this by adding an “empty game object” to the scene, by right-clicking on the hierarchy and selecting “Create Empty” from the context menu. I rename this GameObject to “Tile”. Now the graphic itself could be anything from a 3D object to a sprite. In this first version of the game I use a simple quad. I add one to the “Tile” object I just created by right-clicking the “Tile” and selecting “3D” -> “Quad”. I renamed the quad “TileGraphic”. I added the quad to an empty GameObject to be able to change the graphic in a later stage without needing to change too much in the game. Scripts, translation and scaling will be done on the root object of the tile and not on the graphic. Actually, let’s change the scale of the “Tile” object to 0.9 on all axis. This way I can create a grid of 1 by 1 tiles and have a little space between the tiles.

You might be wondering why I add 3D object to a 2D game. The 2D game is actually still 3D under the cover. Just by configuration, like setting the Camera to orthographic for example, the 3rd dimension somewhat hidden and object don’t appear smaller when further away from the camera.

To make the tile reusable I convert it to a Prefab. A prefab is an object that is stored separate and can be reused easily. To convert the GameObject to a Prefab just drag it from the hierarchy to the Prefabs folder. The GameObject in the hierarchy should turn blue indicating it is a prefab.

Create Prefab

Create Prefab

 

I delete the “Tile” GameObject from the hierarchy now. It should still be available as a prefab.

Generating a level

Time to write some code. To generate a level we need to run some code. I added a new C# script to the scripts folder, by right-clicking the scripts folder and selecting “Create” -> “C# script”. I named the script “LevelController”. Double-click the script to edit it in Visual Studio, which may take a few seconds.

Just a Moment

Just a Moment

 

After Visual Studio opens you’ll end up with a class, inherited from MonoBehavior. This class contains two methods. “Start”, which is called when the script is activated and “Update”, which is called every frame.

using UnityEngine;

public class LevelController : MonoBehaviour
{
    public int NumberOfRows = 7;
    public int NumberOfColumns = 7;

    public GameObject Tile;

    void Start()
    {
        for (int i = 0; i < NumberOfColumns; i++)
        {
            for (int j = 0; j < NumberOfRows; j++)
            {
                Instantiate(Tile,
                            new Vector2(i - NumberOfColumns / 2f + .5f,
                                        j - NumberOfRows / 2f + .5f),
                            Quaternion.identity);
            }
        }
    }
}

The first version of the LevelController just generates a level when the script is activated. It does this by going through two for loops. The two integer fields in the beginning of the class define how many rows and columns the grid will contain. By making these public Unity will show them in the Inspector so these values can be changed design-time. The third field, “Tile”, will be linked to the prefab we created earlier.

Inside both for-loops the Instantiate method is called. This method instantiates a new version of the GameObject passed as its first parameter. The second parameter of the Instantiate method is the position of where the newly instantiated GameObject should be placed. It seems like a whole lot of math for such a simple thing. All it does is centering the grid to the world. The +.5f is added because the tiles are positioned based on their center and not the top-left corner as you might expect. The last parameter, the Quaternion.identity, is the rotation. In this case it basically means to use no rotation.

Make sure the script is saved before heading back to Unity.

In Unity the script has to be attached to something. Because there’s not much in the scene at the moment, I just attach it to the camera by dragging the script onto it. When you look at the Inspector you should see the script, with its properties in there. Last thing to do is to drag the prefab created earlier to the “Tile” property of the script. By now, the inspector should look something like this:

Inspector

Inspector

 

If you were following along you should be able to test-run the game now. You can do this by hitting the play button at the top of the screen in Unity.

Running in Unity

Running in Unity

 

If you haven’t already, this would be a great time to save the scene. Just hit ctrl+s and save the scene under the scenes folder by the name of “Main”.

Running as a Windows app

To run the game as a Windows app we’ll have to change the build settings. You can find the build settings under “File”->”Build Settings…” in the menu.

Build Settings

Build Settings

 

First, make sure the scene is in the build. You’ll probably have to add it by clicking the “Add Open Scenes” button. Next, set the Platform to “Windows Store” and click “Switch Platform”. Change the SDK to Universal 10. To be able to Run and debug from Visual Studio, check the “Unity C# Projects” and “Development Build” checkboxes. Keep in mind that this will create a C# solution with everything you need to run the game. The scripts we’ve edited before are not C# files contained in this project, because they’re Unity scripts that happen to be C# (although they’re linked in there as well).

Hit Build to build the project. You’ll have to specify a folder to build to. I usually create a new folder called “WindowsStoreBuild” and choose that. You can open the solution in Visual Studio and run it from there.

Running as UWP App

Running as UWP App

 

And that’s it for now. In the second part I’m going to add the various colors to the tiles and probably make them clickable.

untitledLast week I was invited by iSense to give a presentation about JavaScript Frameworks in Universal Windows Platform Apps. I decided my personal goal was to show people that JavaScript is a perfectly legit language of writing your apps for Windows 10, specially when you have a web development background.

I started with an introduction about the way the JavaScript UWP apps work in Windows 10 and talked a bit about the great support of ES6 in Microsoft Edge. I then demonstrated how easy it is to convert a web application to a hosted UWP app, including what you could do in case there’s no internet connection when the app is started. I continued by introducing WinJS and showed how to use oauth in a UWP app in a secure way. I created a simple app that shows your subscriptions from YouTube.

After the break I went over the basics of KnockOutJS, in combination with WinJS, and showed the app from the first demo, but rebuild using Knockout. I added a filter to shorted the list of subscriptions.

The last part of the evening was about AngularJS, again in combination with WinJS. I showed the same app again, this time build with Angular. I added another feature, navigation.

I had a great evening and would like to thank iSense for giving the opportunity. Below are the slides if you are interested. The code for the demos will be available on my GitHub soon.

OAuth in a UWP JavaScript app

A quick walkthrough on how to get authenticated with YouTube using oauth, in a JavaScript Universal Windows Platform (UWP) app. It uses a few classes from the Windows Runtime.

The demo code can be found on my github account at:
https://github.com/sorskoot/UWP-OAuth-demo

Guide from YouTube for setting up oauth:
https://developers.google.com/youtube/v3/guides/auth/installed-apps

Documentation of the YouTube API:
https://developers.google.com/youtube/v3/docs/

Getting your own client ID and client secret:
Google developer console – https://console.developers.google.com/
How to obtain credentials – https://developers.google.com/youtube/registering_an_application
More on the oauth flow – https://developers.google.com/youtube/v3/guides/auth/installed-apps

Twitter: @Sorskoot
Weblog: http://winjs.ninja
Channel: http://youtube.com/c/winjsninja

When working on my drum machine app I started changing the look and feel a little. I started my changing the black and gray to some more bright colors. Pretty quickly I ran into some issues with changing the look and feel of the default controls. The blue color is specified as a named color ‘Highlight’, which seems to be controlled by Windows.

After searching for quite a while I came across some MSDN documentation that describe a couple of vendor specific CSS pseudo-classes to alter various elements of the controls. The whole list of pseudo-classes you can use to style controls can be found here.

As an example of how you can do this, this is the CSS to change the sliders from the default blue as shown above to a new design.

input[type=range]::-ms-fill-lower {
    background: hsl(320, 100%, 25.1%);
}

input[type=range]::-ms-fill-upper {
    background: transparent;
}

input[type=range]::-ms-ticks-after, 
input[type=range]::-ms-ticks-before {
    display: block;
    color: hsl(320, 100%, 55.1%);
}

input[type=range]::-ms-thumb {
    background: hsl(320, 100%, 25.1%);
    padding: 3px;
    border: 1px solid hsl(320, 100%, 55.1%);
    border-radius: 4px;
    box-shadow: 0 0 10px black;
}

This will make you sliders look like this:

By default, the Visual Studio Android emulator sets its keyboard entry to the hardware keyboard attached to you PC. But it might be very useful when developing apps to work with the software keyboard on Android. In the Windows Phone emulator, you can use a page-up and page-down to enable and disable the keyboard. In the Android emulator you’ll have to change a setting in the OS itself.

To change the setting, got to the Android Settings and to Language & Input. Than select “Change Keyboard”.


Hit the switch to change the input method.


You’re good to go:


 

 
 

When developing applications in Visual Studio I work with the keyboard most of the time. Throughout the years I learned a lot of short cuts to a lot of features. I’m sure most of you know and use these, too. But there are some features or actions that do not work well with the keyboard. For example closing all open tabs or opening the TFS source control explorer. For actions like this I had to use the mouse, just because it was faster than the keyboard. Until I learned about this feature a while ago.

A couple of versions of Visual Studio ago there was a search box inside the toolbar. This search box can double as a command line. If you are using one of the latest versions of VS the search box is still there, but you’ll have to add it to your toolbar yourself. You can do this by clicking on the little triangle at the end of the ‘standard’ toolbar. Then click ‘Add or Remove Buttons’ and select ‘Find’.

Now the search box is back on the toolbar.

Normally when you type in this box and hit enter you’ll search for the text you’ve typed. But… When you hit ‘Ctrl+/’ on your keyboard the search box gets focus and a ‘ > ‘ is placed in there. Now you can enter commands to Visual Studio. For example, ‘>Window.CloseAllDocuments’ to close all open documents. When typing in this box you’ll notice you can a dropdownlist with completions for the command you’re typing. Because all of these commands a bit long to type you can add aliases for them. So in case of ‘Window.CloseAllDocuments’, I’d rather type ‘wca’. To accomplish this hit ‘Ctrl+/’ and type ‘alias wca window.CloseAllDocuments’. From now on you can type ‘wca’ to close all open documents.

Another command I use regularly is ‘tfs’ to access the TFS source control explorer. You can create this alias with ‘alias tfs Team.TfsSourceControl’.

One more thing I want to mention is that you can add ‘External Tools’ to the command aliases as well. One that I use is ‘cmd’ to open a command prompt at the root of my current selected project. I did this by first creating the ‘external tool’. You can open the window below by going to the tools menu and selecting external tools.

The values I entered are:

  • Title: cmd
  • Command: %windir%\system32\cmd.exe
  • Arguments: “C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat”
  • Initial directory: $(ProjectDir)

There are commands for 24 external tools that can be called in the search box. Mine happened to be the 6th. So I created an alias by typing ‘alias cmd Tools.ExternalCommand6´. From this moment on I can hit ‘Ctrl+/’ and type ‘cmd’ to open a command prompt at the root of my current project. Which I find very useful when working with NPM and Bower.

Let me know in the comments below what commands you are using in this command line.

 

 

Slide3

Today I’m adding an AngularJS service to the Windows Store project in Visual Studio. This service is making a call to an external webservice which returns some JSON data. This controller uses a promise to handle the call to the service and when it’s fulfilled the data is shown on the screen.

You can find the code: https://github.com/sorskoot/AngularWinjsDemo