Phaser for Beginners

Shuffling the tiles

The basics behind shuffling the tiles is to shuffle the array of tile values, that tileArray which will be used to assign each tile its own value. There are a lot of ways to shuffle an array and they all have their roots on random number generation, which is a branch with countless theories. While in a casino game with real money prizes true randomness is really important, in a quick puzzle game this does not make sense, as the basic random functions provide a great deal of randomness which is good enough to have a completely different boards each time we play.

So we are going to change placeTiles function in the most basic way with just randomly switching two tilesArray elements a given amount of times, and numRows * numCols times is enough to have a completely shuffled board.

Change placeTiles function this way:

Now run the game and play, and have another go, then another one, and so on. You will notice each time you start a game, tiles are placed in a different way. That’s enough, and the code involved in this process is just another for loop where at each iteration two randomly chosen elements in tilesArray array are swapped, using a temporary variable because given two values A and B, JavaScript does not allow us to swap A with B, but we can save A value in C variable.

Then assign A the value of B, then assign B the value of C which is the saved A value. What I want you to focus in this loop is how I generate the random numbers to assign to each array index for swapping.

rnd.between(min, max) generates a random integer number ranging from min to max , both included.

And this last feature completes our game, a nice game which nobody will want to play. Although the game runs and works well, you can’t believe people will play games without a theme, without a goal, without any twist. Probably in 1970’s players would have loved your game, but today they won’t.

Are we going to put the entire game in the trashcan?

No, we can still make something interesting out of it, by just adding a couple of features and polish a bit the game.

Download Source

File: shuffling-the-tiles.zip


Next Tutorial →

Adding a title screen with sound/mute options

← Previous Tutorial

Using timers to schedule events