Hiero Match: Add New Challenge "Shuffle Tiles

Part 1 of the Hiero Match series: shuffle the paired tiles every play session with a Fisher–Yates shuffle.

Hiero Match is a matching/pairing game tutorial using Unity3D from the book Unity 3 Blueprints, written by Craig Stevenson and Simon Quig, and published by Deep Pixel. This tutorial spans from chapter 2 through chapter 3.

This post demonstrates how to add new challenges to the game. The first enhancement involves shuffling paired tiles/cards each time the game is played. To begin, you'll need the complete game project files from the book.

Implementation

Add a new function called RandomizeArray to your tileGenerator.js script. This function implements the Fisher–Yates shuffle algorithm by exchanging values:

//the basic idea was Fisher–Yates shuffle algorithm
//by exchanging value a[i] to a[random]

static function RandomizeArray(arr : Array)
{
    //iterate array backwards
    for (var i = arr.length - 1; i > 0; i--) {
        var r = Random.Range(0,i);
        var tmp = arr[i];
        arr[i] = arr[r];
        arr[r] = tmp;
    }
}

Next, call the RandomizeArray() function at the top of the Start() function:

function Start () {
	Camera.main.transform.position = Vector3 (2.25, 2.25, -8);
    //place this line below on top of Instantiate Object
	RandomizeArray(this.tileLocations);
	for (var i=0; i < this.numberOfTiles; i++){
		Instantiate(this.tileObjects[i], this.tileLocations[i], Quaternion.identity);
	}
}

Test the modifications using Unity3D's play button. The tile positions will now randomize with each play session.


This is part 1 of the Hiero Match series.