My example of a sliding puzzle game movement

I’ve been playing around with the classic sliding puzzle game. This is a mix of what I’ve read in this forum as well as previous projects. This is just the mechanics for sliding the tiles. The best part of this is that it not only moves 1 tile but will move an entire row or column. It’s very dynamic. It will work with any tile size or configuration without needing any changes to the events. More on that below.

Try me: (click the tile you want to move. You can move 1 tile or an entire row/column)

Source: (click the green [code] button, select [download zip], unzip and open the json file)

The tiles can be of any size or quantity. They can be a tiled sprite with the image offset on each tile or separate objects. The important part is the tiles MUST be exactly aligned in columns and rows. They can be 3x3 or 4x3. They can be squares or rectangles. The key is to keep them aligned and the same size.

Here is the scene setup.

There are 2 objects. A tiled sprite named “tile” and a sprite named “empty”. The “empty” sprite is used to track the empty space. The “tile” object is in a group in case you want to use separate objects. It doesn’t use any object variables. The “tile” object has the tween behavior.

It uses 3 scene variables; Two numbers named x & y and a Boolean named “FoundTile”

Here are the events:

The tween time and easing style can be tweaked to your liking. The concept is mostly straight forward. It tweens the tiles to the empty space and moves the empty to the tiles old spot. For multiple tiles, it starts from the empty space, uses a ray cast between the empty and clicked tile. It then assigns the tile closest to the empty tile a tween as it works its way from the empty tile to the x,y of the clicked tile. As a tile is given a tween, it is ignored by the ray cast. Once it can’t find a tile, it exits the while event.

Be careful with the while event. It can cause an infinite loop if the events aren’t exact. FYI: the while event is in the tool bar in the menu that opens when you click the + in a circle.

Comments and questions are welcome.