Phaser for Beginners

Checking for successful matches and removing tiles or turning them back

Once we have selected two tiles, then selectedArray has two elements, and we have to check for their values. We will remove the tiles if values match, or cover back them again if values do not match. This means some more lines added to showTile function:

Let’s see the new code in detail:

This is how we check for selectedArray to have two elements, so it’s time to check for tiles to have the same value:

We access value custom property of the first and the second s electedArray elements and check for them to be equal. If they are equal, it’s time to remove the tiles from the stage.

destroy method permanently destroys the button, destroys the input event and animation handlers if present and nulls its reference to game, freeing it up for garbage collection.

It’s the best way to remove the button and never think about it again, so let’s destroy both buttons.

And now we are done when the player selected tiles with the same symbols.

What if tiles have different symbols?

We have to use an extension to if statement called else.

Use the else statement to specify a block of code to be executed if the condition in the if statement is false.

It works this way:

So when the condition “selected tiles have the same value” is false, this is what happens:

We simply change frame properties of both tiles to turn them back again. Finally, no matter whether the tiles have been removed or covered back, we need to empty selectedArray array to let the player select a new couple of tiles.

To empty an array, we set its length to zero:

If you browse the web, you will find another way to empty arrays, for example by setting them back to empty array definition assigning it to [] . I personally prefer setting array length to zero in JavaScript, and an explanation for this reason is beyond the scope of this project.

You are free to choose the way you prefer to empty an array, just make sure selectedArray is now empty or the player won’t be able to select any more tile. Time to run the game, and try to make both matching and non matching selections.

Now matching tiles will be removed from the stage, while non-matching tiles will be covered back. Everything works fine, it’s just you aren’t able to see the second tile you select, are you?

This happens because as soon as you select the second tile, we perform the check for matching tiles and remove/cover selected tiles so fast you can’t even see what happened. This is obviously a bad game design practice, so we will wait a second with the selected tile before removing/covering them.

Download Source


Next Tutorial →

Using timers to schedule events

← Previous Tutorial

Preventing the player to select more than two tiles each turn