For a while now I am streaming the building of a game with the working title ZombieCastlePrincess on Twitch. Although this game itself isn’t open source, I’ve put the editor scripts I build on my GitHub.

These scripts are available:

GroupInto, works on a selection and places the whole selection into a new Empty GameObject.
RandomizeSprites lets you select a list of sprites and places them randomly on the GameObjects with SpriteRenderers you selected.
RenameSelection renames your selection and places a number behind them (like “Grass (2)”).
ReplaceSprite replaces the sprite on the selected GameObject with another you select.
RoundOffColliders rounds the points of a 2D PolygonCollider to the nearest integer.
SelectBySprite selects all GameObjects in a scene that have a certain sprite.
SelectMissingSprites selects all GameObjects that are missing their sprites.

I’m sure this list will grow eventually. If you want to see me use these and build my game check me out on Twitch.

I recently learned about a very cool console.log feature. You can use CSS formatting to style the output of console.log. And it’s very easy. All you have to do is use the ‘ %c ‘ formatting tag in your message. Here’s a simple example:

console.log('%cThis is a %cfun%c console message',
            'font: 24px serif; font-weight:100; color: #228;',
            'font: 30px sans-serif; font-weight:800; color: #F44;',
            'font: 24px serif; font-weight:100; color: #228;'
        );

When you look in the console of the browser, you should see something like this:

fun-console-message

Unfortunately this features is not supported in all browsers, which may result in a whole bunch of CSS being written to the console. You should check the browser in your code before using this feature. As far as I know only Chrome and Firefox support this feature.

Today I was working streaming (https://livecoding.tv/sorskoot) building my new JavaScript Audio Workstation. I wanted to use a template in a custom WinJS control but found it wasn’t in the samples.  Also, the MSDN documentation contained an error which made it even harder to get it to work. Here’s an example:
(function () {
  WinJS.Namespace.define('jsaw.ui', { 
    menuBar: WinJS.Class.define(
      function (element, options) {
        this.element = element || document.createElement('div');
        this.element.winControl = this;
        this.options = options;
        this.createControl();
    }, {
      createControl: function () {
        WinJS.UI.Fragments.render('./app/templates/menubar.html',
                                  this.element)
                          .done(
                                /* Your success and error handlers */
                          );
      }
    })
  });
  WinJS.Class.mix(jsaw.ui.menuBar, WinJS.Utilities.eventMixin);
})();
In this example I create a WinJS class in the jsaw.ui namespace. This class has a constructor function (line 4) that calls the createControl function. In that function (line 10), a fragment is rendered. This fragment serves as a template for the control. All HTML in that control will be rendered and it will be cached as well. Note, that the Fragments object is in the UI namespace.

When I start a new Cordova or Ionic project I normally start from the command line. I initialize the project and add some platforms and packages I need to use in my project. I sometimes start coding from VSCode, but there will be a point where I’d like to switch to Visual Studio, the full version. Until recently I started by creating a new project and move the existing code and config files into that. That was until I came across this awesome feature in Visual Studio: “Create New Project From Existing Code Files”. I don’t know when it was added, but I somehow missed it. Here’s how it works.

Import existing project

I assume you already have an existing piece of code you want to move over to a Visual Studio project. To get it into Visual Studio the easy way, go to File –> New in the menu and select, “Project From Existing Code…”

FileNew

In the dialog that appears make sure “Apache Cordova” is selected in the dropdown list and hit the “Next >” button.

CreateProject

On the next dialog screen you have to navigate to the folder in which you Cordova project is. You also have to give your project a name. Hit “Finish” after that to close the dialog and start the creation of the project. This may take a few seconds.

FolderNameProject

After the project is imported you’ll end up with a solution similar to the one in the image below.

solution

From this point on you can use Visual Studio to work on your Cordova, or Ionic, project.

 

One of the most obvious ways to spot a Cordova app is a pinch-zoom inside the app. On Android and iOS you can use meta-tags and CSS to disable the pinch-zoom and over scroll. But for some reason I couldn’t get it disabled on Windows 10 mobile.

The Solution

I’ve been looking everywhere for the solution. And after a long search it turned out to be very easy. Just add the following CSS to your app:

html {
    touch-action: none;
}

There used to be a Microsoft vender specific version of this, but the vender part is dropped and it’s now according to the W3C standard.

While working on the Cordova Drum Machine I’m currently streaming live at LiveCoding.tv/sorskoot, I ran into a few issues with Visual Studio debugger. Normally I debug my ‘normal’ AngularJS web applications inside Chrome using an extension on the debug tools that shows the context of the selected HTML element. In Visual Studio I do not have these tools available. Here’s how to get information on the Angular context of a selected element.

Scope

The first thing that’s really useful to gain insight to is the Angular scope. The scope has to be read from a specific DOM element. To select an element from your app (in my case I’m running my Cordova app as a UWP app on the Windows desktop), click the ‘select element’ button in Visual Studio and pick the element from your app. In the screenshot below I’ve selected a group of radio buttons from which I’d like to view the current scope.

selectElement

Visual Studio will highlight the DOM element that is selected.

Now we’ll have a look at the JavaScript Console inside Visual Studio. If you type $0 in there and hit enter, the JavaScript Console will prompt the highlighted element. We need this to get the current Angular Scope. The easiest way to get the Angular Scope is by using the angular.element function on the selected element and call the scope function on the result. Like so:

var s = angular.element($0).scope()

At this point the ‘s’ variable contains the entire scope. You’re probably interested in some properties of that.

vm

In my drum machine I only added a property ‘vm’ to my scope that contains the viewmodel. In my case I used this code to debug and find out what the scope contained at for the selected elements.

Controller

Alternatively you might be interested in the controller that is used at the DOM element you have selected. The code to get access to the current controller is very similar to that of the scope. But instead of calling the scope function you have to call the controller function.

var c = angular.element($0).controller()

When evaluating the ‘c’ variable in the console we get to see what’s inside the current controller.

controller

You can look at the current state of all properties inside the controller and even call function on there.

Wrap

Since there is no specific tooling inside Visual Studio 2015 that help you to debug and explore AngularJS inside your application, these functions might help you getting some insights of your app. I would suggest to have a look at the other properties in the result of angular.element($0).

 

A lot of people use jQuery in their HTML/JavaScript applications. There’s nothing wrong with that. But I’ve seen a lot of people use jQuery only to make it easy to find elements and they are not using any of the other jQuery functions. It’s pretty clear that writing a single ‘ $ ‘ instead of the way longer usages of various function on the ‘document‘ object, like getElementById. One of the functions on the ‘document’ object is the querySelectorAll function. This function brings a similar experience to vanilla JavaScript by taking selectors as a parameter.  So if we take a look at the example below. This show a fairly complicated selector you might find in an application.

I personally don’t like writing ‘document.querySelectorAll every time I need to find some things in the DOM, and many people with me. That’s why a lot of developers include jQuery in their project. To be able to use a similar syntax as jQuery is using I often add the following line somewhere at the start of my JavaScript code:

window.$ = function (selector) { return document.querySelectorAll(selector); };

Here’s the earlier example, but with the poor-mans-jQuery added.

It’s not perfect and sometimes I add a context or something to that function if it is needed for that project, but it works fine in most cases.
As a last note, always look at the performance. If you are using selectors a lot, like in a big for-iteration, you might want to use the document.getElementsByClass function or something similar. These have less overhead and are somewhat faster.

During a recent stream over at LiveCoding.TV I ran into some issues with displaying an image in a Cordova app I’m building. This image was stored inside my appx package, but the Content Security Policy blocked it anyways.

It turned out I needed to whitelist the ms-appx and ms-appx-web protocols.

I modified the initialization of the Angular module to whitelist these protocols for images and hrefs as you can see in the example below:

angular.module('app', ['ngRoute'], function ($compileProvider) {
    $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|file|chrome-extension|ms-appx-web|ms-appx):|data:image\//);
    $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|chrome-extension|ms-appx-web|ms-appx):/);
});

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.